1

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');
    });

5 Answers 5

5

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');
        });
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , Worked when I used name="Run"
1
$('#Run').on('change', function () {
     $('input[type=hidden]').val($(this).is(':checked'));
});

is() will return either true or false

DEMO Fiddle

Comments

1

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!');
}

Comments

0

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)

Comments

0

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

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.