4

checkboxFor renders the following for a checkbox:

<input id="IsCredit" name="IsCredit" type="checkbox" value="true" />
<input name="IsCredit" type="hidden" value="false" />

In javascript,

$('#IsCredit').val();

is ALWAYS true. Whether ticked or unticked

How can I determine if the checkbox has been ticked in Javascript?

2
  • if(document.getElementById("#IsCredit").checked){}else{} Commented Sep 28, 2012 at 10:24
  • straight HTML5 check : IsCredit.checked Commented Mar 19, 2019 at 3:14

3 Answers 3

14

You can check it's checked property. With jQuery:

var isChecked = $('#IsCredit').prop("checked");

Or with native DOM methods:

var isChecked = document.getElementById("IsCredit").checked;
Sign up to request clarification or add additional context in comments.

Comments

2

val returns a value of a form element, as your element has a true value, val() returns true not it's checked property value, you can use prop method for reading checked property of a checkbox, or is method.

if ( $('#IsCredit').is(':checked') {
    // ...
} 

or:

var checked = $('#IsCredit').prop('checked');

Comments

0

$("#IsCredit").attr('checked') will tell you if it's checked. You can also use a second parameter true/false to check/uncheck the checkbox.

Per comment, use prop instead of attr when available. E.g:

$("#IsCredit").prop('checked')

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.