Submit form when changing items

In jQuery, if I assign the form class=auto_submit_form form, it will be sent whenever any element is changed, with the following code:

 /* automatically submit if any element in the form changes */ $(function() { $(".auto_submit_form").change(function() { this.submit(); }); }); 

However, if I want the form to be submitted only when the specified elements change:

 /* submit if elements of class=auto_submit_item in the form changes */ $(function() { $(".auto_submit_item").change(function() { $(this).parents().filter("form").submit(); }); }); 

I am just learning jQuery. Is there a better way to do this?

+6
javascript jquery
source share
4 answers
  /* submit if elements of class=auto_submit_item in the form changes */ $(function() { $(".auto_submit_item").change(function() { $("form").submit(); }); }); 

There is only one form per page. If not, you will need to select the form that is the ancestor of the current element using $(this).parents("form").submit()

+20
source share

You can use the expression in the parents() method to filter the parents. Therefore, this may be a little more efficient:

 /* submit if elements of class=auto_submit_item in the form changes */ $(".auto_submit_item").change(function() { $(this).parents("form").submit(); }); 
+10
source share

I would give an id of the form:

 $(".auto-submit-item").change(function() { $("form#auto-submit").submit(); }); 
+4
source share

I came up with a general approach to this:

 $('.autoSubmit, .autoSubmit select, .autoSubmit input, .autoSubmit textarea').change(function () { const el = $(this); let form; if (el.is('form')) { form = el; } else { form = el.closest('form'); } form.submit(); }); 

All form elements:

 <form class="autoSubmit"> <select><option>1</option><option>2</option></select> </form> 

Separate items only

 <form> <select class="autoSubmit"><option>1</option><option>2</option></select> </form> 
+3
source share

All Articles