jquery更新多个字段

时间:2011-04-06 11:37:24

标签: php jquery ajax textbox

代码中有什么问题吗? 它实际上并没有更新所有textinput ,而是仅在点击保存后更新第一个输入id = 1!

HTML标记:

<input type="text" id="1">
<input type="text" id="2">
<input type="text" id="3">
<input type="text" id="4">
<input type="text" id="5">
<input type="text" id="6">

JQUERY:

 $('#save_affiliate').live('click',function() {
            var $inputs = $('#affiliate_form');
            $inputs.each(function(){
                var counter = $(this).find("input[type=text]").length;
                var af_value = $(this).find("input[type=text]").attr("value");
                var af_id = $(this).find("input[type=text]").attr("id");
                if(counter>0){
                    $.post("include/setting.php?affiliate",{id:af_id, text_value:af_value, count:counter}, function(data){
                        if(data.success) {
                                $('.err').html(data.message).fadeIn('slow');
                        } else {$('.err').html(data.message).fadeIn('slow');}
                    },"json");
                }
            });
            return false;
        });

PHP:

$counter = $_POST['count'];
$value = $_POST['text_value'];  
$id = $_POST['id'];
$i = 0;
if ($counter != 0) :
    while($i<$counter) :
    $db->query("UPDATE affiliate SET d_percent='$value' WHERE id_affiliate='$id'");     
    endwhile;

    $data["message"] = "Affiliate percentage value has been changed!";
    $data['success'] = true;
endif;

3 个答案:

答案 0 :(得分:2)

您在表单上使用.each(),但需要在输入中使用它:

$('#save_affiliate').live('click', function() {
    var $inputs = $('#affiliate_form').find("input[type=text]");
    $inputs.each(function(i) {
        var counter = $inputs.length;
        var af_value = $(this).attr("value");
        var af_id = $(this).attr("id");
        $.post("include/setting.php?affiliate", {
            id: af_id,
            text_value: af_value,
            count: counter
        }, function(data) {
            if (data.success) {
                $('.err').html(data.message).fadeIn('slow');
            } else {
                $('.err').html(data.message).fadeIn('slow');
            }
        }, "json");
    });
    return false;
});

您也无需检查counter > 0,因为如果没有input[type=text],该功能将无法运行。如果你的计数键是输入的索引,那么使用传递给每个函数的i参数。

答案 1 :(得分:1)

使用

$(this).find("input[type=text]").each(function(index) {
// 
});

操纵每个捕获的元素。

答案 2 :(得分:0)

正如Stefan的回答所提到的,你需要使用某种循环来迭代你得到的每个输入元素。 原因是tha .attr()方法返回您调用它的元素集中 first 元素的属性。 因此,当您执行

var af_value = $(this).find("input[type=text]").attr("value");
var af_id = $(this).find("input[type=text]").attr("id");

你只是检索id&amp;选择器匹配的第一个输入元素的值;在你的情况下,它是id = 1的那个。