jquery获取复选框checkbox的值

时间:2023-11-20 11:45:14

jQuery API :

each(callback) :以每一个匹配的元素作为上下文来执行一个函数。

:checked :匹配所有选中的被选中元素(复选框、单选框等,不包括select中的option)

js:

//js获取复选框值
var obj = document.getElementsByName("interest");//选择所有name="interest"的对象,返回数组
var s='';//如果这样定义var s;变量s中会默认被赋个null值
for(var i=;i<obj.length;i++){
if(obj[i].checked) //取到对象数组后,我们来循环检测它是不是被选中
s+=obj[i].value+','; //如果选中,将value添加到变量s中
}

jquery:

//jquery获取复选框值
var chk_value =[];//定义一个数组
$('input[name="interest"]:checked').each(function(){
//遍历每一个名字为interest的复选框,其中选中的执行函数
chk_value.push($(this).val());//将选中的值添加到数组chk_value中
});