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:
$('#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.
$("#something-%"). submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });
data() function. Show activity on this post. My tries: if($("input[@name='submit']:clicked"). val() == 'button') $("input[type='button']").
The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form. If you plan to call . submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form's submit method/handler is shadowed by the name/id attribute.
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 });
You can catch all forms by using the selector 'form', e.g.
$("form").submit(function() { var theForm = $(this); var formID = theForm.attr("id"); // do something });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With