Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

javascript - Upon clicking a checkbox, uncheck other checkboxes and trigger change or click event on the on one that was previously checked

I have a group of checkboxes for a filtering functionality that triggers some function upon clicking them. I need to implement one checkbox checked at a time which is not the problem but I need to trigger a click or change event on previously checked checkbox as changing the "prop" did not fire any event.

 <input type="checkbox" data-filter="threebed" class="bedroomsCheck" name="bedrooms" value="three">
 <input type="checkbox" data-filter="fourbed" class="bedroomsCheck" name="bedrooms" value="four">
 <input type="checkbox" data-filter="fivebed" class="bedroomsCheck" name="bedrooms" value="five">

My approach which did not give appropriate output on filtering functionality.

  $(document).on('click', '.bedroomsCheck', function() { 

      $('.bedroomsCheck').not(this).prop('checked', false);
      $('.bedroomsCheck').each( function (){
            if(!(this) && is(':checked')){

               //how do I target the one that meets condition?

             }
      });
 });

 //This didn't work either
 $('.hometypeCheck').not(this).prop('checked', false).trigger('change');   //click, change

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try like this:

var clicked;

$('.bedroomsCheck').on('click', function() {
  clicked = $(this);

  if ($(this).is(':checked')) {
    $('.bedroomsCheck:checked').not($(this)).each(function() {
      $(this).prop('checked', false);
      $(this).trigger('change');
    });
  };
});

$('.bedroomsCheck').on('change', function() {
  if (!clicked.is($(this))) {
    //do something useful here
    console.log($(this).val() + ' changed');
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" data-filter="threebed" class="bedroomsCheck" name="bedrooms" value="three">
<input type="checkbox" data-filter="fourbed" class="bedroomsCheck" name="bedrooms" value="four">
<input type="checkbox" data-filter="fivebed" class="bedroomsCheck" name="bedrooms" value="five">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...