3

How can I change the following to submit on both blur and on submit:

$('form').on('blur', 'input', function(event) { });
user4913694
  • 466
  • 1
  • 8
  • 19

3 Answers3

1

You can pass multiple events to jQuery's on method.

$('form').on('blur submit', function(event) { })

This would mean that whenever the $('form') element was either a) blurred or b) submitted, the event handler would be invoked.

Aweary
  • 2,302
  • 17
  • 26
  • I tried this and it's not submitting when the input is changed (as `blur` does in my question). – user4913694 Jun 15 '15 at 21:52
  • Well, as mentioned, the form will already be submitted when the user clicks the submit button, so this is kind of a weird functionality to ask for. If you want the event handler to submit the form, make sure you're calling `$('form').submit()` within it. – Aweary Jun 15 '15 at 21:53
  • @Aweary - it would be one way of auto-saving the form contents, if the submit was AJAX, [local storage](https://developer.mozilla.org/en/docs/Web/Guide/API/DOM/Storage) would probably be a better solution for that – Toni Leigh Jun 15 '15 at 22:00
  • I understand using blur to save the data, but it doesn't make sense to invoke a `submit` event after a `submit` event. There's no reason to submit the form again if we've just submitted it. – Aweary Jun 15 '15 at 22:40
1

Change your function to a named function expression, then re-use the definition, like this:

var submitFunction = function(event) {
    // stuff
}

$('input[type=text]').on('blur', submitFunction);
$('input[type=submit]').on('click', submitFunction);

Also, you don't need the middle argument to on() - you can just use the $ function to target the elements you want. This means you won't add your click and your blur to all input elements on the form.

Community
  • 1
  • 1
Toni Leigh
  • 4,830
  • 3
  • 22
  • 36
0

you can trigger the submit in blur

$('form').on('blur', 'input', function(event) {
     $('form').trigger('submit');
    // or $('form').submit();
 });

and for your form submit

 $('form').on('submit', function(event) {
      // when form submit ...
   });
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28