如何使用jQuery改变复选框的值
复选框是用来让用户在有限的选择中选择一个或多个选项。:checkbox选择器选择类型为checkbox的输入元素。
语法:
$('#textboxID').val($("#checkboxID").is(':checked'));
在上述语法中,基本上是将选中或未选中的复选框的返回值分配给文本框。下面的例子将说明这个方法。
例子1:这里用函数click()将复选框的返回值分配给文本框,每当复选框被点击检查或取消检查时,它将各自的返回值分配给文本框。因此,如果我们想根据复选在文本框中分配某个用户定义的值,我们可以使用if/else语句来实现。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
// Set initial state
('#textbox2').val((this).is(':checked'));
// It gets checked to false as uncheck
// is the default
('#checkbox1').click(function() {
('#textbox2').val((this).is(':checked'));
});
});
</script>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p>
A Computer Science
Portal for Geeks
</p>
<input type="checkbox" id="checkbox1" />
Check if true, Uncheck if false.
<br><br>
<input type="text" id="textbox2" />
</center>
</body>
</html>
输出:
例子2:这个例子包含一个以上的复选框。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
// Set initial state
('#textbox1').val('no');
// Returns yes or no in textbox1
// when checked and unchecked
('#checkbox1').click(function() {
if (("#checkbox1").is(":checked") == true) {
('#textbox1').val('yes');
} else {
('#textbox1').val('no');
}
});
// Returns male in textbox2 if checkbox2 checked.
('#checkbox2').click(function() {
if (('#checkbox2').is(":checked") == true) {
('#textbox2').val('Male');
} else {
('#textbox2').val('');
}
});
// Returns female in textbox2
// if checkbox2 checked.
('#checkbox3').change(function() {
if (('#checkbox3').is(":checked") == true) {
('#textbox2').val('Female');
} else {
('#textbox2').val('');
}
});
});
</script>
</head>
<body>
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<p>
A Computer Science
Portal for Geeks
</p>
<input type="checkbox" id="checkbox1" />
Check If yes!
<br>
<input type="text" id="textbox1" />
<br>
<input type="checkbox" id="checkbox2" /> Male
<input type="checkbox" id="checkbox3" /> Female
<br>
<input type="text" id="textbox2" />
</center>
</body>
</html>
输出:
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。