Let's say there are multiple checkboxes inside a div (call it "startwars" ) i know how to check and trigger a function if state of checkbox is changed or clicked on all over the page by doing :
$('input[type=checkbox]').click(function() {
console.log("somethign is checked on the page")
});
but what if i want to limit that scope to a div and check if any of checkbox state is changed/clicked which are inside that a div,
I want to trigger a function if any of the checkbox is changed/clicked inside a div element with JQuery
Definition and Usage. The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
add a class or id to the div you want to limit scope of and use it in your selector in jQuery
<div class='limited'>
<input type='checkbox' />
</div
JS
$('.limited input[type=checkbox]').change(function() { // while you're at it listen for change rather than click, this is in case something else modifies the checkbox
console.log("something is checked on the page")
});
You can do it by adding an id or class to the div you want the event to occur in like this: https://jsfiddle.net/oa9wj80x/10/
<div id="slct"">
<h1>
INSIDE
</h1>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<div>
<h1>
OUTSIDE
</h1>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<script>
$('#slct input[type=checkbox]').change(function(){
alert("See it's working");
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With