如何使用Jquery从动态创建的文本框中检索值

时间:2012-05-07 10:03:39

标签: javascript jquery css

我的一个表单允许使用Jquery添加多个元素。以下HTML显示了演示内容

<form name="my-location-frm">
    <div class="address">
        <input type="text" name="house-name" value='house1'>
        <input type="text" name="street-no" value='street1'>
    </div>

    <div class="address">
        <input type="text" name="house-name" value='house2'>
        <input type="text" name="street-no" value='street2'>
    </div>

    <div class="address">
        <input type="text" name="house-name" value='house3'>
        <input type="text" name="street-no" value='street3'>
    </div>

    <input type="submit">
</form>

这里class="address"包装器将重复多次。如何使用Jquery

检索每个元素(house-name,street-no)值

尝试如下,

$.each($(".address"), function(key,value) { 

     hn = $(value).children("input[name=house-name]").val();
     console.log(n);
}

但失败了:(

预期的Javascript输出,

house1,street1
house2,street2
house3,street3

2 个答案:

答案 0 :(得分:4)

请改用此变体:

$(".address").each(function() {
    var house = $(this).children("input[name='house-name']").val();
    var street = $(this).children("input[name='street-no']").val();
    console.log(house + "," + street);
});

或者(如果需要)您可以收集数组中的所有输入值:

$(".address").each(function() {
    var values = [];
    $(this).children("input").each(function() {
        values.push(this.value);
    });
    console.log(values.join(","));
});

DEMO: http://jsfiddle.net/PtNm5/

答案 1 :(得分:1)

$.each($(".address"), function(key,value) { 
     var hn = $(this).children('input[name="house-name"]').val(),
         sn = $(this).children('input[name="street-no"]').val();
     console.log(hn.concat(', ' + sn));
});

OR

 $.each($(".address"), function(key,value) { 
         var hn = $('input[name="house-name"]', this).val(),
             sn = $('input[name="street-no"]', this).val();
         console.log(hn.concat(', ' + sn));
    });

OR

$.each($('.address'), function() {
  var output = $('input[name="house-name"]', this).val().concat(', ' + $('input[name="street-no"]', this).val());
  console.log(output);
});