检查复选框是否已选中如果未选中则添加值否则删除值

时间:2013-10-10 08:30:17

标签: javascript jquery html

我有复选框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>

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

<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';

因此,对于复选框上的每个更改,都应更新变量。我很困惑,如果添加数据=“1”等复选框是否正常?当有单引号时,我通常会为锚点做。

6 个答案:

答案 0 :(得分:2)

<强> Live Demo

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

<强> 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();

答案 1 :(得分:1)

<强> 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

<强> demo

参考 Arrays checked-selector

答案 2 :(得分:1)

您可以使用.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()方法。

答案 3 :(得分:1)

的javascript

getElementById("chkbox1").checked=true;

jquery的

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

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

答案 4 :(得分:1)

试试这个动态的

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);
}
});

Demo Fiddle

答案 5 :(得分:0)

检查此Jsfiddle

$("#btn").click(function(event){
    var selectedvalue=[];
$(":checkbox:checked").each(function(){

selectedvalue.push($(this).attr("data"));

});

alert(selectedvalue.join("-"));// your desired result

  })
相关问题