2012-05-07 33 views
1

我的一个表单允许使用Jquery添加多个元素。下面的HTML显示演示内容,如何使用Jquery从动态创建的文本框中检索值

<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

每个元素(房子的名字,街道没有)值尝试如下,

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

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

但失败:(

预期的Javascript输出,

house1,street1 
house2,street2 
house3,street3 

回答

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

$.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); 
}); 
+0

为什么要投票?评论请 – thecodeparadox

+0

感谢所有帮助我:) – abhis

相关问题