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 clicke开发者_如何学Cd?
I assume you're binding to the submit
event on the forms. Use serialize
instead of querying for values:
$('form').submit(function(){
$.post('edit.php', $(this).serialize(), function(data) {
alert("Data Loaded: " + data);
});
return false;
});
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:
$.post("edit.php", { id: $(this).find("input[name=id]").val(), action: "Edit" },
function(data){
alert("Data Loaded: " + data);
});
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 the name="id"
<input>
in the <form>
you're in the submit handler of.
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:
$("#myform").find("#id").val()
Use the form element that is submitted as a context in your selector:
$('form').live('submit', function(e) {
var form = $(this);
var id = $('#id', form).val();
//... do your post here
});
NOTE: I used .live() to bind to the submit event in case you're adding forms dynamically.
精彩评论