views:

779

answers:

3

In jQuery, if I assign class=auto_submit_form to a form, it will be submitted 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 to the form to submit only when specified elements are changed:

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

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

+2  A: 
 /* submit if elements of class=auto_submit_item in the form changes */
$(function() {
   $(".auto_submit_item").change(function() {
     $("form").submit();
   });
 });

Assumes you only have one form on the page. If not, you'll need to do select the form that is an ancestor of the current element using $(this).parents("form").submit()

tvanfosson
using "this.form.submit();" would be even better because you wouldn't have to instantiate the jQuery object.
nickf
+1  A: 

You can use an expression in the parents() method to filter the parents. Hence this might 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();
});
Darko Z
A: 

I would give an id to the form:

$(".auto-submit-item").change(function() {
    $("form#auto-submit").submit();
});
Murat Ayfer