2017-05-31 27 views
1

当每个复选框检查复选框时jquery创建输入 我怎样才能得到所有名称输入?如何获取同名多个文本?

如果选中复选框创建输入:

<script> 
function dynInput(cbox) { 
    if (cbox.checked) { 
     var input = document.createElement("input"); 
     input.type = "text"; 
     input.className = "cbox"; 
     var div = document.createElement("div"); 
     div.className = "cbox-div"; 
     div.id = cbox.name; 
     div.innerHTML =cbox.name; 

     div.appendChild(input); 
     document.getElementById("insertinputs").appendChild(div); 
    } else { 
     document.getElementById(cbox.name).remove(); 
    } 
}</script> 

复选框,然后输入:

 <form class="add-item"> 
      <input type="checkbox" onclick="dynInput(this);" name="1"> 1<br> 
      <input type="checkbox" onclick="dynInput(this);" name="2"> 2<br> 
      <input type="checkbox" onclick="dynInput(this);" name="3"> 3<br> 
      <input type="checkbox" onclick="dynInput(this);" name="4"> 4<br> 
     </form> 
     <p id="insertinputs"></p> 

我只能得到第一个输入值:

var item = $(".cbox").val(); 

    console.log(item); 
+0

这样做,因为作为val的文档状态()只返回集合中的第一项。您需要遍历集合并读取每个项目的值。 – epascarello

回答

1

您需要遍历所有的输入如:

$(".cbox").each(function(){ 
    var item = $(this).val(); 
    console.log(item); 
}); 
+0

它的工作 tnx –

+0

这很棒。欢迎@LintonSamuelDawson ......':)'! – vijayP

1
var item=[]; 
$(".cbox").each(function(){ 
item.push($(this).val()); 
}); 
0

因为documentation指定val(),它只返回集合中的第一个项目。您需要遍历集合并读取每个项目的值。

所以你需要遍历集合并建立列表。你可以用每()或地图()

var vals1 = []; 
 
$('[type="checkbox"]').each(function() { 
 
    vals1.push(this.value); 
 
}); 
 

 
var vals2 = $('[type="checkbox"]').map(function() { 
 
    return this.value; 
 
}).get(); 
 

 
console.log("vals1", vals1.join(",")) 
 
console.log("vals2", vals2.join(","))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="checkbox" value="a"> 1<br> 
 
<input type="checkbox" value="b"> 2<br>

1
var items = document.querySelectorAll('.cbox'); 

var values = []; 

items.forEach(function(item) { 
    values.push(item.value); 
}); 

console.log(values); 
相关问题