如何在jQuery中检查一个复选框是否被选中
prop()和is()方法是我们可以在jQuery中检查一个复选框是否被选中的两种方法。
prop():该方法提供了一个简单的方法来跟踪复选框的状态。它在每个条件下都能很好地工作,因为每个复选框都有checked属性,指定它的checked或unchecked状态。
is():这个方法也非常简单,易于使用。通过使用它,我们可以很容易地发现一个复选框是否被选中。
使用jQuery prop()方法:
语法:
$(selector).prop(parameter)
参数:这里的参数是Checkbox的当前状态。
示例-1:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div style="width: 80px;
height: 80px;
padding: 10px;
border: 2px solid green;">
<input type="checkbox"
name="radio1"
checked />
<script>
(document).ready(function() {
("#but").click(function() {
if ($("input[type=checkbox]").prop(
":checked")) {
alert("Check box in Checked");
} else {
alert("Check box is Unchecked");
}
});
});
</script>
<br>
<button style="margin-top:10px"
id="but"
type="submit">
Submit
</button>
</div>
</body>
</html>
输出:
在点击按钮复选框被取消点击之前:
点击按钮后:。
使用jQuery is()方法:
语法 :
$(selector).is(parameter)
参数:这里的参数是Checkbox的当前状态。
示例-2:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 80px;
height: 80px;
padding: 10px;
border: 2px solid green;
}
button {
margin-top: 10px;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div>
<input type="checkbox"
name="radio1"
checked />
<script>
(document).ready(function() {
("#but").click(function() {
if ($("input[type=checkbox]").is(
":checked")) {
alert("Check box in Checked");
} else {
alert("Check box is Unchecked");
}
});
});
</script>
<br>
<button id="but"
type="submit">
Submit
</button>
</div>
</body>
</html>
输出:
在点击按钮的复选框被点击之前:
点击按钮后:。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。