How to connect button to input without form? I wan

2019-08-09 05:26发布

So I am not suppose to use the form tag on this input field (causes bug per backend guy)

How would I be able to allow the user to use the enter key when the input is selected/active to activate the submit?

The user can manually click the add group submit button, or they can tab click, but they can't just enter to click :(

enter image description here

The form

<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);
        }
    });
});

3条回答
成全新的幸福
2楼-- · 2019-08-09 05:50

You can use keypress event

$('#group-code').on('keypress', function (e) {
    var keyCode = e.which;
    if (keyCode == 13) {
        //Trigger click event
        $('#btn_join_group').trigger('click');
    }
});
查看更多
该账号已被封号
3楼-- · 2019-08-09 05:52

You could add a listener to the input something like this:

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

Then wrap your AJAX block in a function called sendAjax. This code is untested, but the idea should be valid.

查看更多
The star\"
4楼-- · 2019-08-09 06:05

Add keypress event to the input and check if the enter key pressed if true trigger the button function.

$('input').on('keypress',function(event){
 if(event.keyCode == [the enter key code])
   //trigger the button click
})  
查看更多
登录 后发表回答