选中复选框是否选中,则添加值,如果未选中则删除值

check if checkbox is checked add value else if unchecked remove value

本文关键字:删除 如果 复选框 添加 是否      更新时间:2023-09-26

我有复选框html。

<label><input type="checkbox"><span>Air Conditioning</span></label>
<label><input type="checkbox"><span>Cable TV Service</span></label>
<label><input type="checkbox"><span>Private Bathroom</span></label>

我需要为每个复选框提供单独的值,以便我可以从所有复选框中获取这些值并存储在变量中。例如

<label><input type="checkbox" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>

因此,如果选择了所有 3 个,我将需要我的变量作为

room_features = '1-2-3';

如果取消选中任何一个,变量将更新为

room_features = '2-3';

因此,在复选框上的每个更改中,变量都应更新。我很困惑添加 data="1" 等是否适合复选框?当有单双引号时,我通常会为锚点做。

现场演示

您应该在每个复选框中使用。 例如:

.HTML:

<input type="checkbox" value="1" checked />
<input type="checkbox" value="2" checked />
<input type="checkbox" value="3" />

JQuery:

var searchIDs = $("input:checkbox:checked").map(function(){
        return this.value;
    }).toArray();

html

<label><input type="checkbox" checked="checked" data="1"><span>Air Conditioning</span></label>
<label><input type="checkbox" checked="checked" data="2"><span>Cable TV Service</span></label>
<label><input type="checkbox" data="3"><span>Private Bathroom</span></label>

.JS

 var selectedvalue=[];
    $(":checkbox:checked").each(function(){
    selectedvalue.push($(this).attr("data"));
    });
alert(selectedvalue.join("-"));// your desired result

演示

参考数组选中选择器

您可以使用

.map()方法,请注意,我已经value属性添加到元素而不是data因为输入应该有一个值,否则使用它有什么意义?如果要使用data-*属性,则应指定标识符。像<input type="checkbox" data-id="1">这样的东西,那么你可以使用jQuery data()方法获取值:$(elem).data('id');

<label><input type="checkbox" value="1"><span>Air Conditioning</span></label>
...

var vals = $('input[type=checkbox]:checked').map(function(){
     return this.value; // return $(this).data('whatever');
}).get().join('-');

get()返回一个数组,如果需要数组,可以删除返回字符串的.join()方法。

试试这个动态的

var room_features = "";
$('[type=checkbox]').change(function () {
var data = "-" + $(this).attr('data');
if (room_features.indexOf(data) != -1) {
    room_features = room_features.replace(data, "");
    alert(room_features);
} else {
    room_features = room_features + data;
    alert(room_features);
}
});

演示小提琴

JavaScript

getElementById("chkbox1").checked=true;

jquery

$("#chkbox1").prop("checked");

$("#chkbox1").attr("checked");

检查这个Jsfiddle

$("#btn").click(function(event){
    var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("data"));
});
alert(selectedvalue.join("-"));// your desired result
  })
相关文章: