使用 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.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/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