如何在 j 查询中获取变量/非常量复选框 id 和值



我正在从sql数据库中获取所有社区名称,并显示带有复选框的下拉列表。 为此,我使用 for-each 循环来显示值。

下面是我的代码$results从数据库中获取数组并将其显示在复选框中

    <div class="btn-group">
    <button type="button" data-toggle="dropdown" title="Columns">
    Columns
    <b class="caret">
    </b>
   </button>
    <ul class="dropdown-menu">
    <?php  foreach( $results as $result){ 
    ?>
    <li>
    <label class="checkbox">
    <input type="checkbox" id="<?php echo $result['community_name']; ?>" 
    name="multiselect" value="<?php echo $result['community_name']; ?>"><? 
    php echo $result['community_name']; ?></input>
    </label>
    </li>
    <?php } ?>
    </ul>
    </div>   

那么如何在Jquery中获取所有选中和未选中的值呢?

请帮忙

谢谢

对每个复选框都有一个共同的className,以便于查询具有相同类的元素。另外,请注意,<input />元素为空,它只能包含属性,不能包含正文。

var cb = $('.cb');
var cbValue = cb.map((index, el) => {
  return el.checked;
});
console.log('cbValue', JSON.stringify(cbValue));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-group">
  <button type="button" data-toggle="dropdown" title="Columns">
    Columns
    <b class="caret">
    </b>
   </button>
  <ul class="dropdown-menu">
    <li>
      <label class="checkbox" for="1">1</label>
      <input type="checkbox" id="1" name="multiselect" value="" class="cb" checked />
    </li>
    <li>
      <label class="checkbox" for="2">2</label>
      <input type="checkbox" id="2" name="multiselect" value="" class="cb" />
    </li>
    <li>
      <label class="checkbox" for="3">3</label>
      <input type="checkbox" id="3" name="multiselect" value="" class="cb" />
    </li>
  </ul>
</div>

$("input[type=checkbox]").on("change", function() {
  $('input[type=checkbox]').each(function() {
    if ($(this).is(":checked")) {
      console.log($(this).attr('id'), "checked")
    } else {
      console.log($(this).attr('id'), "Unchecked")
    }
  });
})
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container">
    <h2>Form control: inline checkbox</h2>
    <p>The form below contains three inline checkboxes:</p>
    <form>
      <label class="checkbox-inline">
      <input type="checkbox" id="opt1">Option 1
    </label>
      <label class="checkbox-inline">
      <input type="checkbox" id="opt2">Option 2
    </label>
      <label class="checkbox-inline">
      <input type="checkbox"id="opt3">Option 3
    </label>
    </form>
  </div>
</body>
</html>

最新更新