Ahmish
Ahmish

Reputation: 1151

How to avoid duplicate submission for single input forms?

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.

Upvotes: 1

Views: 232

Answers (3)

John Strickler
John Strickler

Reputation: 25421

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

Upvotes: 0

Keith.Abramo
Keith.Abramo

Reputation: 6955

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

This will fire when the input loses focus.

Upvotes: 0

Rob W
Rob W

Reputation: 348992

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

Upvotes: 2

Related Questions