Samson
Samson

Reputation: 352

How to remove checkboxes after matching values using jQuery?

I have 4 checkboxes if I select 1 check box then I will get 1 or more sub values and if I select 2nd check box then I will get 1 or more sub values Here My Problem is If I uncheck the 1st check box then I have to remove unchecked check box values not with second check box 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>

Upvotes: 0

Views: 67

Answers (1)

Eddie
Eddie

Reputation: 26844

  • You can construct your cars variable as object. Using the checkbox value as key.
  • Use change as event
  • Use $('.search-box1:checked') selector to get all checked .search-box1 and use map to loop thru the objects.
  • Use join() to make the array into a string(comma seperated).

$('.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>

Upvotes: 2

Related Questions