user2237168
user2237168

Reputation: 303

How to get id and value for each field? JQuery

Dear stackoverflowers,

I have a question about getting the id and value for a specific field. Right now, i have the following code:

<div class="category_edit_form">
    <input type = "text" name = "category_edit_text" class = "category_edit_text" id = "'.$category->category_id.'">
    <input type = "button" class="category_edit_button" value = "Wijzig">
</div>

This is the output of a foreach loop. So each category which is displayed, holds a textfield and a button to change the name. This is my jQuery:

jQuery(".category_edit_button").click( function() {
    jQuery.ajax({
        async: false,
        url: nieuwsbrief.updatecategory,
        type: 'POST',
        data: { category_id: jQuery('.category_edit_text').prop('id'), category_name: jQuery('.category_edit_text').val()},
        success: function(data) {
            alert(data);
        }
    });
}); 

This is the data to alert:

echo $_POST['category_id']."en de naam is: ".$_POST['category_name'];

But each time when i click on any button, i only see the value and the id of the first field. So when i click on the button of the second textfield, the id and the value of the first field pops up instead of the id and the value of the second textfield.

How can i solve this problem?

Upvotes: 1

Views: 468

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

Use instead of that:

jQuery('.category_edit_text').prop('id')

this code:

jQuery(this).prev('.category_edit_text').prop('id')

or prevAll() if not directly the previous element

Upvotes: 0

Jamiec
Jamiec

Reputation: 136114

You need to scope the selectors getting .edit_category_text

jQuery(".category_edit_button").click( function() {
    var $parent = $(this).parent();
    jQuery.ajax({
            async: false,
            url: nieuwsbrief.updatecategory,
            type: 'POST',
            data: { category_id: jQuery('.category_edit_text',$parent).prop('id'), category_name: jQuery('.category_edit_text',$parent).val()},
                success: function(data) {
                        alert(data);
                }
    });

}); 

Upvotes: 0

Kasyx
Kasyx

Reputation: 3200

Use:

jQuery(".category_edit_button").click( function() {

    jQuery.ajax({
            async: false,
            url: nieuwsbrief.updatecategory,
            type: 'POST',
            data: { category_id: jQuery(this).parent().find('.category_edit_text').prop('id'), category_name: jQuery('.category_edit_text').val()},
                success: function(data) {
                        alert(data);
                }
    });

}); 

Upvotes: 1

Related Questions