Enable click event when another checkbox

I need a jQuery function that does the following: for example, when checked checkbox1, when I click on some other elements (with an identifier starting with element-), I could print idthese elements in the console:

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

I tested this example and did not work. I do not know when I am wrong.

+4
source share
2 answers

The easiest way to do this is to invert your logic. That is, place the click handler on the required elements and within this check the status of the flag. Try the following:

$(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>
Run codeHide result
+5
source

I tested it and it will work for you.

$("input[id^=d]").on("click", function() {
    var id = $(this).prop("id");
    if ($("#c1").is(":checked")) {
        console.log(id);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Dogs <input id="c1" type="checkbox" />
Cats <input id="d1" type="checkbox" />
Zebras <input id="d2" type="checkbox" />
Rhinos <input id="e1" type="checkbox" />
Run codeHide result
0

Source: https://habr.com/ru/post/1668535/


All Articles