How to connect button to input without form? I wan

2019-08-09 05:40发布

问题:

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 :(

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

回答1:

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.



回答2:

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:

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