Mithun
Mithun

Reputation: 153

Checkbox value is always returning false

I have a checkbox

<input id="Run" name="Run" value="true" type="checkbox">

<input name="Run" value="false" type="hidden">

and When I try to get the value it always returns false

 $('#Run').val()

"False"

I tried to get the value using .prop

$('#Run').prop('checked')

but I still get the value as false

I also tried

 $('#Run').on('change', function () {
        $('#Run').val($(this).is(':checked') ? 'True' : 'False');
    });

Upvotes: 1

Views: 13799

Answers (5)

Puneet
Puneet

Reputation: 1

Apart from various functions like .is(':checked'), .prop('checked'), .attr('checked'), you can try using the wild card selectors if your control is in update panel like

To get all the elements starting with "mock" you should use:

$("[id^=mock]")

To get those that end with "mock"

$("[id$=mock]")

See also the JQuery documentation

Upvotes: 0

Satish Kumar sonker
Satish Kumar sonker

Reputation: 1288

if you only want to access checkbox property then try this one.

 $(document).ready(function () {
        $('#Run').on('change', function () {
           alert($(this).is(':checked'));
        });
    });

if you only want to access checkbox property and assign to hidden input then try this one.

 $(document).ready(function () {
        $('#Run').on('change', function () {
            $('input[name="Run"]').val($(this).is(':checked') ? 'true' : 'false');
        });
    });

Upvotes: 5

Cheezy Code
Cheezy Code

Reputation: 1715

You always set checked=true for checkboxes instead of value=true.

<input type="checkbox" checked="true"/>

to check it value you need to check as

var boolean = $('#idOfCheckbox').is(':checked');

It the attribute checked that is important This is same in case of radiobuttons as well.

Value is used for textboxes(input type=text)

Upvotes: 0

Thomas Orlita
Thomas Orlita

Reputation: 1627

function checkCheckbox() {
    document.getElementById('RunHidden').value = document.getElementById('Run').checked;
}
<input id="Run" name="Run" value="true" onchange="checkCheckbox()" type="checkbox">
<input id="RunHidden" name="RunHidden" value="false" type="text">

Check if checkbox Run is checked:


Pure JavaScript:

if(document.getElementById('Run').checked) {
    alert('Checked!');
}

jQuery:

if($("#Run").is(':checked')) {
    alert('Checked!');
}

Upvotes: 1

Rino Raj
Rino Raj

Reputation: 6264

$('#Run').on('change', function () {
     $('input[type=hidden]').val($(this).is(':checked'));
});

is() will return either true or false

DEMO Fiddle

Upvotes: 1

Related Questions