简体   繁体   中英

Check if checkbox with specific id is checked JQuery

Please help me how to identify if a checkbox with specific id is checked/unchecked.

<input name="A" id="test" type="checkbox" value="A" /> 
<input name="B" id="test" type="checkbox" value="B" />
<input name="C" id="test1" type="checkbox" value="C" />
<input name="C" id="test1" type="checkbox" value="D" />

If i check the checkbox with id="test" and name="a", then the event should fire and otherwise it should not for rest of the checkbox with different id other than "test"

Please help

Since you tag JQuery you can find it helpful

AAA <input type="checkbox" id="test" />
BBB <input type="checkbox" id="test1" />
CCC <input type="checkbox" id="test2" />

and

$( "input" ).on( "click", function() {
  // for a specific one, but you can add a foreach cycle if you need more 
  if($('#test').is(":checked")){
      alert('is checked!');
  }else {
      alert('is NOT checked!');
  }
});

Element IDs in a given document must be unique! Hence, change your HTML to something like below and take a look at the script.

 $(function() { $(":checkbox").on("change", function() { //When the id is test1 //And name is A //And it's checked if (this.id === "test1" && this["name"] === "A" && this.checked) { alert ("Checkbox with name A and ID test1 is checked"); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="A" id="test1" type="checkbox" value="A" /> <input name="B" id="test2" type="checkbox" value="B" /> <input name="C" id="test3" type="checkbox" value="C" /> <input name="C" id="test4" type="checkbox" value="D" />

Id's must be Unique.... otherwise when you use document.getElementById();

It will select First occurence of specific Id...

Instead implement like this..

<input name="A"  type="checkbox" value="A" /> 
<input name="B"  type="checkbox" value="B" />
<input name="C"  type="checkbox" value="C" />
<input name="C"  type="checkbox" value="D" />

and trigger a event on click oncheck box and use document.getElementsByName('');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM