如何获得每个字段的ID和值? JQuery的

时间:2013-06-04 11:04:59

标签: jquery button input textfield

亲爱的stackoverflowers,

我有一个关于获取特定字段的ID和值的问题。现在,我有以下代码:

<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>

这是foreach循环的输出。因此,显示的每个类别都包含一个文本字段和一个用于更改名称的按钮。这是我的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);
        }
    });
}); 

这是要提醒的数据:

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

但每次当我点击任何按钮时,我只会看到第一个字段的值和id。因此,当我单击第二个文本字段的按钮时,会弹出第一个字段的id和值,而不是第二个文本字段的id和值。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

使用:

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);
                }
    });

}); 

答案 1 :(得分:0)

您需要确定选择器的范围.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);
                }
    });

}); 

答案 2 :(得分:0)

使用而不是:

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

此代码:

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

prevAll(),如果不是直接上一个元素