Search code examples
jqueryform-submitonchangeonfocus

jquery onchange/onfocus on form


I am using jQuery to get an onchange effect of an input text field on my form.

Assume the form has an id="myForm", and input text field has an id="myText";

$('#myText').change(function(){
    $('#myForm').submit();
});

This way, my form is submitted when I change the field and then click outside the field.

HOWEVER, I want my form to be submitted when I am done inserting my data in the input field without having to click outside the input field (losing onfocus).

Any ideas? Is that possible? Thanx


Solution

  • The problem you face is that you need to detect when the user has finished entering information into the text box. On change would be when any key press results in new contents in the textbox, which would be triggered the first letter they enter. I think your only solution for this would be to look at registering at the end of every keyup event a 2 second timeout to submit the form which you cancel if they type another letter.

    So for example:

    var timedSubmit;
    
    $('#myText').keyup(function(e) {
        if (e.keyCode) == 13 { $("#myform").submit() }
        clearTimeout(timedSubmit);
        timedSubmit = setTimeout('$("#myform").submit()', 2000);
    });
    

    Note I have looked for the enter key being pressed (keycode 13) too so that it simply submits the form when enter is pressed.