Search code examples
javascriptjqueryevent-handlingjquery-validatejquery-forms-plugin

Binding jQuery change function to submit function


I'm unable to trigger a form submission upon changing its input. I think I need event handling but I've never really learned what that is.

Here's my HTML:

<form action="/upload">
  <input type="file" name="file">
</form>

Here's my JS:

$('input').change(function(e){
var closestForm=$(this).closest("form");
    closestForm.submit(function(e) {   
  closestForm.ajaxSubmit({   
              success: function(data){
                    console.log('form submitted successfully');
              }
      }); //ajaxSubmit
    return false;
  }); //submit 
}); //change

Please note I'd like to do the submit using AJAX but that isn't the issue as I have other parts of my codebase where I'm able to use the jQuery Form plugin ajaxSubmit() no problem.

Thoughts?


Solution

  • Since you want submit form on input change. you don't require submit event on form

     $('input').change(function(e){
        var closestForm=$(this).closest("form"); 
          closestForm.ajaxSubmit({   
                      success: function(data){
                            console.log('form submitted successfully');
                      }
              }); //ajaxSubmit
            return false; 
        }); //change