Search code examples
jqueryformsjquery-forms-plugin

bind ALL forms at once to jQuery Form possible?


Via ajaxCall I dynamically created a list of users, each user in a seperated form, handling moderator actions. Like:

<form id="'.$aSpeler['playerID'].'">
  <select name="aktieopspeler">
    <option value="" disabled selected>Kies actie</option>
    <option value="vakantiemodusIN">Vakantiemodus IN</option>
  </select>
  <input type="submit" value="OK">
</form>

All my forms are handled by the jQuery Form plugin (malsup). The only solution I can think of, is also creating bindings for each form, but is it possible to bind all forms at once?

Code I use for an existing form:

var options = { 
    target:'#maincontent',   // target element(s) to be updated with server response 
    url:  'backend/admin_speler.php',    // override for form's 'action' attribute 
    type:  'post'       // 'get' or 'post', override for form's 'method' attribute 
}; 
// bind to the form's submit event 
$('#frm_zoek_speler').submit(function() { 
    // inside event callbacks 'this' is the DOM element so we first 
    // wrap it in a jQuery object and then invoke ajaxSubmit
    $(this).ajaxSubmit(options); 
    return false; 
});

using: jQuery v2.1.3


Solution

  • You can bind a single event to a element parent to all desired forms:

    $("#parent").on('submit', 'form', function(){
        $(this).ajaxSubmit(options); 
        return false;
    });
    

    In case you're using a jQuery version previous than 1.7, you can use:

    $("#parent").delegate('form', 'submit', function(){
        $(this).ajaxSubmit(options); 
        return false;
    });