Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On change of any checkbox inside a div trigger a function

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

like image 637
Hassan Naseer Avatar asked Dec 23 '15 21:12

Hassan Naseer


People also ask

What is Onchange in checkbox?

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.

How do I check if a checkbox is checked in an event?

addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });

Do something on checkbox is checked Javascript?

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.


2 Answers

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")
});
like image 156
SoluableNonagon Avatar answered Sep 27 '22 21:09

SoluableNonagon


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>
like image 26
Adam Buchanan Smith Avatar answered Sep 27 '22 21:09

Adam Buchanan Smith