1

I have a single input form:

<form id="my_form">
  <input id="my_input" type="text" />
</form>

In most browsers, when a user types text in this single input and hits 'enter' the form is submitted. That's great but I want to go one step further and make it so that if the user types something and focus is lost, the form is submitted.

I've currently tapped into jQuery's change event like so:

$("my_input").change(function() {
  $("my_form").submit();
});

This works for the case when I change the input value and focus out but if I change the input value and hit 'enter' then the form is submitted twice (once for 'enter' and once for change).

I was starting to go down the path of lower level listening to keys and managing a submit state but figured I'd throw it out to the community to see if anyone knows of a cleaner way.

3 Answers 3

2

Instead of messing with error-prone checks, you can also attach a submit event to the form. If the value is equal to the old value, don't submit the form by using ev.preventDefault().

var oldvalue = "";
$("#my_form").submit(function(ev){
    var newvalue = $("#my_input", this).val();
    if(newvalue == oldvalue) ev.preventDefault(); //Same value, cancel submission
    else oldvalue = newvalue;
})
Sign up to request clarification or add additional context in comments.

1 Comment

Very clean solution, I would suggest to control with some flags but yours is far way better
0

Have you tried the blur event http://api.jquery.com/blur/

This will fire when the input loses focus.

Comments

0

Just an improvement to Rob W's solution.

$('#my_form').submit((function () {
   //Enclose variables as to not pollute the global namespace
   var oldValue,
       input = $('#my_input');  //cache your input

   //Same concept as Rob W's solution
   return function (e) {
       var newValue = input.val();

       if(newValue === oldValue) {
          e.preventDefault();
       }

       oldValue = newValue;
   };
})());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.