Jump to content

checking/unchecking box based on a click of a DIV containing the checkbox


galvin

Recommended Posts

 

Say  I will have multiple DIVs/Checkboxes getting dynamically created, like this...

 

<div class='player' onClick='check()';> <input id='checkbox' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check()';> <input id='checkbox' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check()';> <input id='checkbox' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check()';> <input id='checkbox' name='checkbox' type='checkbox'/></div>

 

I want to make it so if a user clicks a DIV, it will check (or uncheck) only the checkbox that is contained within that DIV, using something like...

 

function check() {
if (document.getElementById("checkbox").checked=false) {
  	document.getElementById("checkbox").checked=true;
} else {
  	document.getElementById("checkbox").checked=false;

 

What is the best way to do it so that it knows to check (or uncheck) only the checkbox within the DIV that is clicked?

 

I assume I could create a variable that increments for each div/checkbox that gets created and give each checkbox a unique ID like...

<div class='player' onClick='check(1)';> <input id='checkbox1' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check(2)';> <input id='checkbox2' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check(3)';> <input id='checkbox3' name='checkbox' type='checkbox'/></div>
<div class='player' onClick='check(4)';> <input id='checkbox4' name='checkbox' type='checkbox'/></div>

 

And then write the proper JS function to process the number that is returned.

 

But is there an easier way, using maybe "this" or something?  Or is my assumption the best/most efficient way?

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.