php - Several jQuery forms
I have several forms on one page, they're all the same, but have different hidden values:
<?php foreach ($results as $result): ?>
<form method="POST" action="edit.php">
<input type="hidden" name="id" value="<?php echo $result['id']; ?>">
<input type="submit" name="action" value="Edit">
</form>
<?php endforeach; ?>
I want id to be submitted using $.post when this is clicked to edit.php, however if I use $("#id").val() (I'm trying to post the hidden input which is named id), it only selects the first id value in the page, and not the one that was clicked by the submit button.
$.post("edit.php", { id: $("#id").val(), action: "Edit" },
function(data){
alert("Data Loaded: " + data); //im using fancybox here to display an inline frame
});
How can I submit the id of the current form clicked?
Answer
Solution:
I assume you're binding to the
submit
event on the forms. Useserialize
instead of querying for values:Answer
Solution:
Since you still need to include the submit's name/value pair, find the
name="id"
input within the<form>
you're on, like this:id
attributes should be unique in the document, since your markup in the question doesn't have an ID it looks like you fixed that issue. This finds thename="id"
<input>
in the<form>
you're in the submit handler of.Answer
Solution:
Do you have multiple page elements with the same ID? Using $("#id").val() I believe would only retrieve the first value of an element with that ID. Having more than one would result in an array of elements. To find a specific element that is duplicated you would have to put it into context like:
Answer
Solution:
Use the form element that is submitted as a context in your selector:
NOTE: I used .live() to bind to the submit event in case you're adding forms dynamically.