php - Several jQuery forms

282

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?

600

Answer

Solution:

I assume you're binding to thesubmit event on the forms. Useserialize instead of querying for values:

$('form').submit(function(){

    $.post('edit.php', $(this).serialize(), function(data) {
        alert("Data Loaded: " + data);
    });

    return false;
});
400

Answer

Solution:

Since you still need to include the submit's name/value pair, find thename="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 thename="id"<input> in the<form> you're in the submit handler of.

470

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:

$("#myform").find("#id").val()
546

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Problems with getFlash and setFlash in Yii

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.