我有一个具有不同值的复选框的列表。
<input type="checkbox" value="55" id="myId">
<input type="checkbox" value="65" id="myId">
<input type="checkbox" value="75" id="myId">
<input type="checkbox" value="85" id="myId">
<input type="checkbox" value="95" id="myId">
当我使用js获取这些值时,它只需要value=55
。这是由于相同的id="myId"
造成的
var x = "";
$("input[type='checkbox']").change(fucntion(){
if(this.checked){
x = x+","+x;
}
});
运行时,它将只加载55
值,如-:55,55,55,55
发布于 2018-07-21 22:23:40
属性id
应唯一。您可以使用数组而不是字符串变量。然后,只需根据复选框状态添加或删除项目:
var x = [];
$("input[type='checkbox']").change(function(){
if(this.checked){
x.push(this.value);
}
else {
var index = x.indexOf(this.value);
x.splice(index, 1);
}
console.log(x.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" id="">55
<input type="checkbox" value="65" id="">65
<input type="checkbox" value="75" id="">75
<input type="checkbox" value="85" id="">85
<input type="checkbox" value="95" id="">95
发布于 2018-07-21 22:32:32
如果选择顺序不重要,可以在每次更改时将选中的值map()
到新数组中
您的字符串连接方法没有考虑取消选中之前选中的输入
$(':checkbox').change(function(){
var vals = $(':checkbox:checked').map(function(){
return this.value
}).get()
console.log(vals.join())
})
// insert values as text for demo
.wrap(function(){
return $('<label>',{text:this.value})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" >
<input type="checkbox" value="65" >
<input type="checkbox" value="75">
<input type="checkbox" value="85" >
<input type="checkbox" value="95" >
请注意,ID在页面中必须是唯一的
发布于 2018-07-21 22:36:37
首先,不要在页面上使用多个相同的id,id在整个页面上应该是唯一的,请尝试使用数据属性
$("input[type='checkbox']").change(function(){
var x = "";
$("[data-id=myId]").each(function(){
if(this.checked){
x = x + $(this).val() + ",";
}
});
console.log(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" data-id="myId">
<input type="checkbox" value="65" data-id="myId">
<input type="checkbox" value="75" data-id="myId">
<input type="checkbox" value="85" data-id="myId">
<input type="checkbox" value="95" data-id="myId">
https://stackoverflow.com/questions/51456884
复制相似问题