1

function handleCheckboxClick(event){

    if(document.getElementById(event.target.id).checked){

      document.getElementById(event.target.id.concat("_visible")).setAttribute("checked", "true");
      console.log(document.getElementById(event.target.id.concat("_visible")));		   				   		
  }
}

var requiredCheckboxes = document.getElementsByClassName("checkbox_required");

for (var i = 0, max = requiredCheckboxes.length; i < max; i++){
   requiredCheckboxes[i].addEventListener('click', handleCheckboxClick);		    
}
<table>    			
	<tr>
		<th>
			Property
		</th>
		<th>
			Visible
		</th>
		<th>
			Required
		</th>
	</tr>
	
	<tr>
		<td>
			Email  
		</td>
		<td>
			<input type="hidden" name="_email_visible" /><input type="checkbox" name="email_visible" id="donation_email_visible"  />
		</td>										
		<td>
			<input type="hidden" name="_email" /><input type="checkbox" name="email" class="checkbox_required" id="donation_email"  />
		</td>
	</tr>
	
</table>

First, click on the required checkbox for Email. As expected the visible box is also checked. Now, check off visible box and click on Required checkbox corresponding to email which will checkoff required box for email. Now click on the required checkbox for email again, the visible checkbox will not be checked. So, here is where my dilemma lies. What is the reason during this second time when clicked on required, why is the visible box not checked? I appreciate your help! Thanks!

1
  • 4
    document.getElementById(event.target.id) is a really long winded way of saying event.target Commented Dec 3, 2015 at 8:11

1 Answer 1

6

The checked attribute determines the default state of a checkbox. Changing it with JS will only alter the current state of a checkbox if the user hasn't modified it.

The checked property determines the current state of a checkbox. Use that instead.

i.e.

Change any instances of setAttribute("checked", "checked") (nb: true is not a valid value for that attribute) to checked = true and any instances of removeAttribute("checked") to checked = false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.