2014-01-17 30 views
1

因此,我不假設在此輸入字段上使用表單標記(導致每個後端人員的bug)如何將按鈕連接到無窗體輸入?我希望用戶能夠使用輸入密鑰

我將如何能夠允許用戶使用當輸入被選擇/激活以激活提交時,回車鍵?

用戶可以手動點擊Add Group提交按鈕,也可以點擊標籤,但他們不能隨便進入點擊:(

enter image description here

形式

<input type="text" 
     id="group-code" value="Type your Group Code Here" name="Type your Group Code Here" 
     onblur="if (this.value == '') {this.value = 'Type your Group Code Here';}" 
     onfocus="if (this.value == 'Type your Group Code Here') {this.value = '';}" 
     autocomplete="off"/> 

<button class="btn" id="btn_join_group">add group</button> 
<!--<input type="submit" id="btn_join_group" form="group-code" value="add group"/>--> 

jQuery

$('#btn_join_group').unbind('click').bind("click", function(event) { 

    var newGroup = $('#group-code').val(); 

    // Send Group code to server 
    WHOAT.networking.getToServerWithAjax('/groups/join', newGroup, function (response) { 
     var res = JSON.parse(response); 

     if (res.result === 'success') { 
      notification.setStatusAndFadeStatus(response); 

     } else if (res.result === 'error') { 
      notification.setStatusAndFadeStatus(response); 
     } 
    }); 
}); 

回答

1

你可以添加一個偵聽輸入是這樣的:

$('#group-code').keypress(function (e) { 
    if (e.keyCode === 13) 
     sendAjax(); 
}); 

然後換你的AJAX塊在一個名爲sendAjax功能。此代碼未經測試,但該想法應該是有效的。

+0

謝謝!這確實有用,而且我最終還是使表單工作,只需要返回false –

+1

我很高興我可以幫助@LeonGaban! –

1

您可以使用keypress事件

$('#group-code').on('keypress', function (e) { 
    var keyCode = e.which; 
    if (keyCode == 13) { 
     //Trigger click event 
     $('#btn_join_group').trigger('click'); 
    } 
}); 
1

將按鍵事件添加到輸入,並檢查如果真的按下回車鍵觸發按鈕功能。

$('input').on('keypress',function(event){ 
if(event.keyCode == [the enter key code]) 
    //trigger the button click 
})