Modify jQuery autocomplete not to submit eagerly on Enter

后端 未结 4 959
悲哀的现实
悲哀的现实 2021-01-14 22:55

Our users complain that when they press the enter key after pasting or typing values in a jQuery autocomplete widget the form is submitted.

It\'s extremely annoyin

4条回答
  •  心在旅途
    2021-01-14 23:36

    I might have a simpler solution by using jQuery autocomplete's autocompleteclose and autocompleteopen events.

    See the code below:

    var flag = 0; //global variable
    
    $("#autocomplete").on({
        autocompleteclose: function (event, ui) {
            flag = 1;
            //set flag back to 0 with a short delay so the next keypress can submit form
            setTimeout(function () {
                flag = 0; 
            }, 100);
        },
        //if the autocomplete widget is open, don't submit form on keypress
        autocompleteopen: function (event, ui) {
            flag = 1;
        }
    });
    
    $('body').keypress(function(e) {
        if (e.keyCode == '13') {
            if (flag != 0) {
                e.preventDefault();
            } else {
                //submit form
            }
        }
    });​
    

    var flag = 0; //global variable
    
    $("#autocomplete").on({
        autocompleteclose: function (event, ui) {
            flag = 1;
            //set flag back to 0 with a short delay so the next keypress can submit form
            setTimeout(function () {
                flag = 0;
            }, 100);
        },
        //if the autocomplete widget is open, don't submit form on keypress
        autocompleteopen: function (event, ui) {
            flag = 1;
        }
    });
    
    $('body').keypress(function (e) {
        if (e.keyCode == '13') {
            if (flag != 0) {
                e.preventDefault();
            } else {
                //submit form
            }
        }
    });
    
    
    $('form').submit(function () {
        alert('You submitted the form');
        return false;
    });
    
    $('#autocomplete').autocomplete({
        source: ["c#", "c", "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    });
    
    
    
    
    
    Type C and press Enter:

提交回复
热议问题