Tron Tron - 7 months ago 14
HTML Question

Need to call function 1 time no matter which checkbox is clicked first - some variation of .one()

I have a page with many products on it, and all the products are of the same type. I have built a filtering function with checkboxes for the products. When the page loads, all the products load, and the checkboxes by default are un-checked.

GOAL: When the user FIRST clicks a checkbox to filter the products, no matter which box is clicked, I would like a specific function to run only one time, in this case, hiding all the products. When I use .one(), it is working once for each checkbox, which is not my desired outcome. I need it to run one time, period. No matter which checkbox is clicked.

Below is the HTML and jQuery, any help is much appreciated, and thank you for your time.

HTML:

<div class="col-md-3 test-one"><label><input id="fourth-cbox" type="checkbox" value="fourth_checkbox" />FOURTH COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="first-cbox" type="checkbox" value="first_checkbox" />FIRST COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="second-cbox" type="checkbox" value="second_checkbox" />SECOND COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="third-cbox" type="checkbox" value="third_checkbox" />THIRD COLLECTION</label></div>


jQuery:

$(document).ready(function() {

$(".test-one").one('click',function(){
$('div[data-product]').parents("li").hide();
});

});

Answer

$(document).ready(function() {
    var test = true;//set to true
   $(".test-one").change(function() {
     if(test){//will run only once during var true
       alert('one')
       test =false;//set to false
       }
     
   });

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3 test-one"><label><input id="fourth-cbox" type="checkbox" value="fourth_checkbox" />FOURTH COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="first-cbox" type="checkbox" value="first_checkbox" />FIRST COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="second-cbox" type="checkbox" value="second_checkbox" />SECOND COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="third-cbox" type="checkbox" value="third_checkbox" />THIRD COLLECTION</label></div>

Do like this

  1. set a variable to true.
  2. check variable if true run function then set to false.
  3. function will not run because variable is now false.