2012-11-20 47 views
1

我的問題是,當我點擊我的按鈕時,它會正常工作,但如果我使用輸入按鈕,它會嘗試提交表單並將?var = x附加到URL 。在Ajax中使用輸入按鈕提交表單

我的兩個輸入:

<input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()"> 
    <input type="button" name="submitbtn" onclick="showUser(users.value)"> 

您可以查看我的其他來源。如果你輸入1或2並點擊按鈕,你會得到結果,但是如果你按下回車鍵,它不會給你結果,並改變URL,正如我所說的。

http://crystalarcade.com/shoutbox

+1

http://stackoverflow.com/questions/5839707/why-is-input-form-appending-when-enter-key-is-pressed – ua741

+0

@Ajgreene中, 5839707上的答案顯示瞭如何使用jQuery提交事件,這將是一種更清晰的方式來處理這種情況。 –

回答

4
您使用 document.getElementById所以給你的按鈕,一個id

這樣

<input type="text" name="users" onkeydown="if (event.keyCode == 13) document.getElementById('submitbtn').click()"> 
<input type="button" id="submitbtn" name="submitbtn" onclick="showUser(users.value)"> 

,這將工作

+0

AH CRAP我剛剛注意到我把名稱而不是id ...我是個白癡。一秒鐘,讓我試試看。 – AJGreene

+0

即可解答。謝謝大聲笑。這樣一個簡單的錯誤。一旦可以,我會將其標記爲答案。 – AJGreene

+0

@ user1817082沒問題開心編碼:) – rahul

0

我假設你有一個表格只有兩個輸入元素。有了jQuery,你可以做這樣的事情:

有些事情應該讓你開始,但我需要做一個筆記,但是這段代碼沒有經過測試,因爲我不能使用AJAX做跨站請求。

<script type="text/javascript"> 
$(function(){ 
    $("#username").on("keypress", function(e){ 
     if(e.keyCode==13){ //keyCode value of 13 is for the enter key 
     $.get("getusers.php" $("#userSearchForm").serialize(), function(data){ 
      if(data){ 
       $("shoutboxtxt").text(data);  
      }     
     }, "text"); 
    } 
    } 
});​ 
</script> 

<form id="userSearchForm"> 
    <input type="text" name="users" id="username" /> 
    <input type="button" name="submitbtn" id="submitbtn" value="Search" /> 
</form> 

<div id="shoutboxtxt"><b>Person info will be listed here.</b></div>​ 

在線瀏覽:http://jsfiddle.net/HwcN3/1/

+0

,我需要向您指出您在腳本標記中引用了jQuery源代碼,但並未真正使用它。現在將是開始使用它的真正好時機。我正在考慮[this](http://crystalarcade.com/shoutbox)網站。 編輯:忘記包括鏈接到您的網站。 – hyde