Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable click event when another checkbox is cheched

I need a jQuery function that does the following thing: for example, when checkbox1 is checked, when I click on some other elements (with an id starting with element-) I could print the id of these elements in the console as follows:

$('#checkbox1').click(function() {
    if ($(this).is(':checked')) {
        $(document).on('click','[id^=element-]', function(e) {
            console.log(this.id);
        });
    } else {}
});

I tested this example and it's not working. I have not idea when I'm wrong.

like image 254
bobc82 Avatar asked Dec 05 '25 06:12

bobc82


1 Answers

The simplest way to do this would be to invert your logic. That is to say, place the click handler on the required elements and within that check the state of the checkbox. Try this:

$(document).on('click', '[id^="element-"]', function(e) {
  if ($('#checkbox1').is(':checked'))
    console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>
  <input type="checkbox" id="checkbox1" />
  Check me!
</label>

<div>
  <button id="element-foo">Foo</button>
  <button id="element-bar">Bar</button>
</div>
like image 51
Rory McCrossan Avatar answered Dec 07 '25 20:12

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!