使用jQuery匹配值后如何删除复选框?

时间:2019-05-22 09:58:18

标签: javascript jquery

如果我选择1个复选框,那么我有4个复选框,那么我将获得1个或多个子值;如果我选择第二个复选框,那么我将获得1个或多个子值。我的问题是,如果我取消选中第一个复选框,则我必须删除未选中的复选框值,而不要删除第二个复选框的values()。

$('.search-box1').on("click", function(e) {

  var inputVal1 = $(this).val();
  var cars = ["Saab", " Volvo", " BMW", " ABC", " HONDA", " TVS"];
  $(".arrVal").html(cars);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="row">
  <div>
    <label>First Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="First Page">
  </div>

  <div>
    <label>Second Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Second Page">
  </div>

  <div>
    <label>Third Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Third Page">
  </div>

  <div>
    <label>Fourth Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Fourth Page">
  </div>
</div>

<div class="arrVal"></div>

1 个答案:

答案 0 :(得分:2)

  • 您可以将cars变量构造为对象。使用复选框 值作为键。
  • 使用change作为事件
  • 使用$('.search-box1:checked')选择器获取所有选中的.search-box1,然后使用map遍历对象。
  • 使用join()将数组变成字符串(逗号分隔)。

$('.search-box1').on("change", function(e) {

  var inputVal1 = $(this).val();
  var cars = {
    value1: ["Saab", "Volvo", "BMW"],
    value2: ["ABC", "HONDA", "TVS"],
    value3: [],
    value4: [],
    value5: [],
  }

  var result = $('.search-box1:checked').map(function() {
    return cars[this.value] || [];
  }).get();

  $(".arrVal").html(result.join());

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="row">
  <div>
    <label>First Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value1">
  </div>

  <div>
    <label>Second Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value2">
  </div>

  <div>
    <label>Third Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value3">
  </div>

  <div>
    <label>Fourth Page</label>
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value4">
  </div>
</div>

<div class="arrVal"></div>