JavaScript与jQuery判断及设置Checkbox选中状态的方法

作者:函数茶馆时间:2026-10-25 13:58:38浏览:472

本文介绍如何使用原生JavaScript和jQuery判断复选框是否选中,以及如何设置其选中状态。原生JS通过getElementById获取元素并操作checked属性,jQuery则利用.prop()方法或.is()方法实现相同功能,提供具体代码示例供参考。

判断Checkbox选中状态的方法

本文介绍一个常见的前端功能:判断复选框(checkbox)是否被选中,以及在操作完成后将其设置为选中状态。你可以参考以下代码实现这些需求。

首先,介绍如何判断复选框是否处于选中状态。

使用原生JavaScript实现:

if(document.getElementById("insDown").checked){

}

接下来,展示如何使用jQuery来实现相同的功能。

方法一:使用 $(checkbox的id).prop("checked"),该方法返回一个布尔值(boolean)。

方法二:使用 $(this).is(":checked"),同样返回一个布尔值。

设置Checkbox选中状态的方法

其次,介绍如何将复选框设置为选中状态。

使用原生JavaScript实现:

document.getElementById("insDown").checked=true;

使用jQuery实现:

$("#insDown").prop("checked", true);

此外,还可以使用以下jQuery代码设置选中状态: $("#cb1").prop("checked","checked"); $("#cb1").prop("checked",true);

以下是完整的代码示例。


//第几个没有选 

<input type="checkbox" name="checkbox1" checked> 
<input type="checkbox" name="checkbox1"> 
<input type="checkbox" name="checkbox1" checked> 
<input type="checkbox" name="checkbox1"> 
<input type="checkbox" name="checkbox1"> 
<script language=javascript> 
function check(obj) 
{ 

for(i=0;i<document.all(obj).length;i++) 
{ 
if(!document.all(obj)[i].checked)alert("第"+(i+1)+"个没有选择") 
} 
} 
</script> 
<input type=button onclick="check('checkbox1')" value="检测"> 
//一个也没有选 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<Script Language="JavaScript"> 
function check(obj){ 
for(i=0;i<document.all(obj).length;i++){ 
if(document.all(obj)(i).checked){ 
return; 
} 
} 
window.alert('一个也没有选!'); 
} 
</Script> 
<input type=button onclick="check('test');" value="检测"> 

//第几个没有选 
<input type="checkbox" name="checkbox1" checked> 
<input type="checkbox" name="checkbox1"> 
<input type="checkbox" name="checkbox1" checked> 
<input type="checkbox" name="checkbox1"> 
<input type="checkbox" name="checkbox1"> 
<script language=javascript> 
function check(obj) 
{ 

for(i=0;i<document.all(obj).length;i++) 
{ 
if(!document.all(obj)[i].checked)alert("第"+(i+1)+"个没有选择") 
} 
} 
</script> 
<input type=button onclick="check('checkbox1')" value="检测"> 


//一个也没有选 


<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<input type="checkbox" name="test"> 
<Script Language="JavaScript"> 
function check(obj){ 
for(i=0;i<document.all(obj).length;i++){ 
if(document.all(obj)(i).checked){ 
return; 
} 
} 
window.alert('一个也没有选!'); 
} 
</Script> 
<input type=button onclick="check('test');" value="检测">

文章到此结束,如需更多相关内容,请查看本站以往发布的文章。

作者最新文章