Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the value of checkbox?

HTML :

<input type="checkbox" aria-checked="false" class="cloud-private" value="" data-spm-anchor-id="a800.io">

My java script :
( i want to click this checkbox if it is not checked ,but this does not work )

var z = document.getElementsByClassName('cloud-private'); 
if (z[0].aria-checked=='false'){ 
    z[0].click(); 
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Should not be using aria-checked here in this way. Should be using the checked attribute as is shown in the checkbox spec on MDN.

let cloudPrivateCbxs = document.querySelectorAll('.cloud-private');

if (cloudPrivateCbxs && !cloudPrivateCbxs[0].checked) { 
    cloudPrivateCbxs[0].click();
}

Here I used a useful variable names (never use single letter variable names except for simple counters like those in for loops), used querySelectorAll instead of getElementsByClassName, then I first check if the variable contains anything, then I simply check the checked attribute to see if it returns false. It is returning a boolean so I can use the logical NOT operator ! rather than check directly if it is equal to false.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading