0

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.

Amit jha
  • 7
  • 1
  • 6

2 Answers2

0

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>
Oen44
  • 3,156
  • 1
  • 22
  • 31
  • I just want to query about a particular checkBox of ID :SecurityVulnerability_SecurityVulnerability – Amit jha Apr 13 '17 at 20:43
  • – Amit jha Apr 13 '17 at 20:51
  • You are trying jQuery here, not JavaScript. Be specific next time. Copy my code, if you are using jQuery then your question should be closed, you didn't say anything about using jQuery. – Oen44 Apr 13 '17 at 20:59
-1

You can just read whether it is checked or not.

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

https://jsfiddle.net/sLx9926o/

jas7457
  • 1,712
  • 13
  • 21
  • And, how do you know that the `id` will be `checkbox`? Your answer doesn't actually address the question, which was how to do this with a Razor generated textbox. – Scott Marcus Apr 13 '17 at 20:34
  • I can see id from inspect element in chrome. Id is :SecurityVulnerability_SecurityVulnerability – Amit jha Apr 13 '17 at 20:36
  • That's not true, Scott. The question is "How to get Value of CheckBox in Javascript if its already Checked?" or in the question itself, "If a Check Box is Checked or Unchecked and we stored this value in Database, then How can we get that Value in JavaScript?" - I answered that. – jas7457 Apr 13 '17 at 20:38
  • – Amit jha Apr 13 '17 at 20:39