使用JQuery获取多个复选框选中值的最佳方法是什么 [英] What is the best ways to get the multiple checkbox checked value using JQuery
问题描述
<div class="myBox">
<input type = "checkbox" id = "Banana" value = "Banana" />
<input type = "checkbox" id = "Orange" value = "Orange" />
<input type = "checkbox" id = "Apple" value = "Apple" />
<input type = "checkbox" id = "Papaya" value = "Papaya" />
<input type = "checkbox" id = "Watermelon" value = "Watermelon" />
<input type = "checkbox" id = "Grape" value = "Grape" />
</div>
<div id="display">
</div>
如何将其存储到数组中并将所有复选框选中的值显示在#display中当有人选中复选框时立即div,并在取消选中某个复选框时删除该值。例如,当我点击Banana然后#displaydiv将显示Banana并且我继续点击Grape然后它将显示Banana,Grape。取消选中复选框时,从#displaydiv中删除Banana一词,这样#displaydiv将只显示Grape。在Jquery。
How to store it into array and display all the check-box checked value into the "#display" div immediately when someone is checked the check-box and also remove the value when someone is unchecked the check-box. For example, When I click on Banana then the "#display" div will display Banana and I continue to click on Grape then it will display Banana, Grape. Remove the word "Banana" from the "#display" div when unchecked the check-box so the "#display" div will only display "Grape". In Jquery.
非常感谢任何帮助。
推荐答案
使用 map()
函数获取选中的值...和 join()
以使用<连接数组code>,。
using map()
function to get the checked values... and join()
to join the array with ,
.
试试这个
$('.myBox input:checkbox').change(function(){
var tempValue='';
tempValue=$('.myBox input:checkbox').map(function(n){
if(this.checked){
return this.value;
};
}).get().join(',');
$('#display').html(tempValue);
})
OR
简单方法
$('.myBox input:checkbox').change(function(){
var tempValue='';
tempValue=$('.myBox input:checkbox:checked').map(function(n){ //map all the checked value to tempValue with `,` seperated
return this.value;
}).get().join(',');
$('#display').html(tempValue);
})
这篇关于使用JQuery获取多个复选框选中值的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!