简体   繁体   中英

How to get Value of CheckBox in Javascript if its already Checked?

If a Check Box is Checked or Unchecked and we stored this value in Database, then How can we get that Value in JavaScript?

Here is my code:

<div class="editor-label" style="width: 110px;">
     <%: Html.LabelForEx(model => model.SecurityVulnerability.SecurityVulnerability) %>
</div>

<div class="editor-field" style="width: 60px; padding-top: 0;">
      <%: Html.CheckBoxFor(x => x.SecurityVulnerability.SecurityVulnerability) %>
</div>

Now If I loaded the page then check Box might be checked or not. If it is checked then I want to get this value as true(or whatever) or if not checked then false in JavaScript(I am writing some javaScript Function). I tried using onclick function but that only work when user do check and uncheck in UI Manually. Also if User clicks on UI manually then also I want to get value accordingly.

I am quite new to javaScript and razor.

When page is fully loaded, it iterates through all checkboxes and logs it's check state.

 window.onload = function() { var checkBoxes = document.querySelectorAll('input[type="checkbox"]'); for(var i = 0; i < checkBoxes.length; i++) { console.log(checkBoxes[i].checked); } } 
 <label>I'm checked <input type="checkbox" value="foobar" checked></label><br> <label>I'm not checked <input type="checkbox"></label> 

If you have only one unique input (with ID) then you can do that.

 window.onload = function() { var checkBox = document.getElementById("SecurityVulnerability_SecurityVulnerability"); console.log(checkBox.checked); } 
 <label> Checked<input type="checkbox" id="SecurityVulnerability_SecurityVulnerability" checked></label> 

You can just read whether it is checked or not.

var checkbox = document.getElementById('checkbox');
alert(checkbox.checked);

https://jsfiddle.net/sLx9926o/

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