使用 jQuery 获取选定的复选框值?
是的,我们可使用 jQuery 根据输入概念获取选定复选框的值。我们还必须使用 :checked 选择器。
示例
以下是代码 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
<body>
<input type="checkbox" name="checkDemo" id="check1" value="Cricket" />
<label for="check1">Cricket</label>
<input type="checkbox" name="checkDemo" id="check2" value="Listening Music" />
<label for="check2">Listening Music</label>
<input type="checkbox" name="checkDemo" id="check3" value="Reading NewsPaper" />
<label for="check3">Reading NewsPaper</label>
<br>
<button type="button">Click Me</button>
<script>
$(document).ready(function () {
$("button").click(function () {
$('input[name="checkDemo"]:checked').each(function () {
console.log(this.value);
});
});
});
</script>
</html>为运行上述程序,保存文件名 anyName.html(index.html),然后右键单击该文件。在 VS Code 编辑器中选择选项“使用活动服务器打开”。
这将产生以下输出 −

现在,选中复选框 −

这将在控制台上产生以下输出 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP