Mark
Mark

Reputation: 5028

Generalization of JQuery submit function

In my web application I have dozen of forms, of course each one with a different id. Then in my JavaScript file I wrote a custom handler for the submit event:

$('#form-name').submit(function(event) {
    event.preventDefault();
    const formData = new FormData($('#form-name')[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
});

I want to avoid to write the above code for each form. As first step I can just wrap it in another function, something like this:

function custom_submit(form, event) {
    event.preventDefault();
    const formData = new FormData($(form)[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
}

and then use:

$('#form-name').submit(custom_submit('#form-name`, event));

but this is not a valid syntax. In any case I still need to "connect" each form to the custom function, writing two times its name.

Is there a way to match all the forms that have a specific prefix and connect all of them to my custom submit function passing both the form id and the event variable as above? Example of prefix:

form-ws-*

Upvotes: 2

Views: 53

Answers (2)

Nitin S
Nitin S

Reputation: 7591

Best solution will be to create a jQuery plugin and then attach it to the desired forms (in this you can give any jquery selector).

usage:

$("<SELECTOR>").submitify();

(function($) {
  $.fn.submitify = function() {
    var $this = $(this);
    $this.on('submit', function(event) {
      event.preventDefault();
      const formData = new FormData(this);
      const json = JSON.stringify(Object.fromEntries(formData));
      console.log(json);
      //ws.send(json);
    });
    return this;
  };
}(jQuery));

$(document).ready(function() {
  $('[id^=form-ws-]').submitify();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <form id="form-ws-f1" class="col-md-4">
      <input type="text" class="form-control" name="t1" id="t1" />
      <input type="submit" value="submit" />
    </form>
    <form id="form-ws-f2" class="col-md-4">
      <input type="text" class="form-control" name="t2" id="t2" />
      <input type="submit" value="submit" />
    </form>
    <form id="form-ws-f3" class="frm col-md-4">
      <input type="text" class="form-control" name="t3" id="t4" />
      <input type="submit" value="submit" />
    </form>
  </div>
</div>

JsFiddle here: https://jsfiddle.net/nitinjs/650guLhr/15/

Upvotes: 1

mplungjan
mplungjan

Reputation: 177786

$('form').on('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
}); 

will handle all forms on the page

Upvotes: 3

Related Questions