How to check with jQuery if any form is submitted?

Lozzano picture Lozzano · Feb 20, 2013 · Viewed 68.7k times · Source

I have a page with a lot of forms, and the user is going to pick something on that page. When the user does, I need to place that element somewhere else, much like a shopping cart really. But I can't seem to get more than the first form on the page to actually work as intended. I've tried multiple things:

  1. Give all forms the same ID, which only caused the first form to act as I wanted, giving me the data of that form.
  2. Give them all the same ID again, this time appending a unique identifier to the ID, but of course, then my jQuery $('#something') doesn't catch it since it doesn't match.

So I am thinking how I would go about this. I need to only recieve the data from the submitted form on the page. And as mentioned, I could give them all a prefix of some sort, like I have now, but then I don't know how to match it.

Help would be greatly appriciated!

Some code as requested (only an example to show what I mean, of course):

The HTML:

<form id="something-0"><input type="hidden" value="0"><input type="submit"></form>
<form id="something-1"><input type="hidden" value="1"><input type="submit"></form>

The jQuery:

$("#something-%").submit(function(e) {
e.preventDefault();
$("#some-span").html(data);
});

I want the #something-% to accept anything that comes after the "-", I hope you understand.

Answer

gilly3 picture gilly3 · Feb 20, 2013

As a general answer, to classify a group of elements, use the class attribute, giving each element the same class name. You can then select elements by that class. An element can have more than one class.

$(".something");

If you must use id, you can use an attribute selector:

$("[id^='something']");  // all elements with an id beginning with 'something'
$("[id$='something']");  // all elements with an id ending with 'something'

For this specific question, since you want to act on any form within the page, the simplest choice would be to use the element name selector:

$("form");

Regardless of the selector, you can identify which form was submitted by referencing this within the submit() handler:

$("form").submit(function (e) {
    e.preventDefault();
    var formId = this.id;  // "this" is a reference to the submitted form
});