0

So, I have my MVC 3 view (Razor), with a form. Now it loads up the template which loads up all the scripts it uses, I put this at the top of the form:

<script type="text/javascript">
    $(function () {
        $('#App_RunFromUSB').change(function () {
            alert($('#App_RunFromUSB').val());
        });
    });
</script>

Which basically means that if the checkbox on the form is checked then alert the user of its value.

Simple, so why does it keep showing true in the alert box....

I put it in a fiddle and it does the same thing, JS Fiddle

2
  • for checkbox it will always show true as you have provided value to checkbox. you should check whether the checkbox is checked or not using jquery and then show appropriate message Commented Mar 19, 2013 at 9:47
  • possible duplicate of jquery checkbox value Commented Mar 19, 2013 at 9:50

3 Answers 3

1

Value is not changed because it's a checkbox. It's the property checked that gets changed, you can check it by using:

 $('#App_RunFromUSB').change(function () {
     alert($('#App_RunFromUSB').is(':checked'));
 });

See following DEMO: http://jsfiddle.net/Dwb7N/2/ to confirm. So the value alway remains the same.

Sign up to request clarification or add additional context in comments.

6 Comments

how could you, on start up, check whether the checkbox is checked and change elements accordingly?
The answer to your new question has already been given, echoing out the answer it's: $('#App_RunFromUSB').is(':checked');
i know that bit... its the "on start up, change elements part"
What code do you have so far? Like I said it's the same thing so you could have: $(document).ready(function(){ if ($('#App_RunFromUSB').is(':checked')) { then do some stuff here} });. Comments have limited formatting so I hope you can understand that sample.
well because it is inline on a view I use $(function() {}); instead of $(document).ready(); which seems to work, thanks
|
1

If you are just wanting to alert the true/false depending on if the checkbox is checked or not, then update your code to;

alert($('#App_RunFromUSB').is(':checked'));

An example of your code with the change can be found here http://jsfiddle.net/Dwb7N/3/

Comments

0
<script type="text/javascript">
    $(function () {
        $('#App_RunFromUSB').change(function () {
            alert($('#App_RunFromUSB').is(':checked'));
        });
    });
</script>

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.