Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy giá trị checkbox đã chọn bằng jQuery


Dùng jQuery selector input[name="checkDemo"]:checked kết hợp each() để lấy giá trị các checkbox được chọn.

Ví dụ

Mã HTML và JS:

<!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>

Mở file bằng Live Server, chọn checkbox và nhấn nút để xem kết quả console.

Kết quả

Hình ảnh minh họa giao diện và console log.