2012-05-07 35 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

相關問題