Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript value for CheckboxFor

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?

like image 877
ChrisCa Avatar asked Dec 04 '22 14:12

ChrisCa


2 Answers

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;
like image 50
James Allardice Avatar answered Dec 25 '22 13:12

James Allardice


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');
like image 36
undefined Avatar answered Dec 25 '22 13:12

undefined