3

I am trying to change input value of a checkbox when it is checked/unchecked. It seems the value is changed (I debugged it via alert()) but is not reflected in the html. That's quite troublesome as I want to pull the value from the html and save it in a database.

                $(document).ready(function(){
                    $("#box:checked").live('click', function(e) {
                        $("#box").val('1');                          
                    });

                    $("#box:not(:checked)").live('click', function(e) {
                        $("#box").val('0');                            
                    });    
                 });

    ... 

      <input id="box" type="checkbox" value="">

    ...

I've been trying to solve this for hours. I came upon a guy who had the same problem, but the workaround was rather clumsy.

thanks for help

4
  • The HTML source cannot be changed... if that is what you mean. Commented Sep 6, 2011 at 14:52
  • When you say it's not reflected in the HTML, what exactly do you mean? The markup showed when "View Source" is clicked is not going to change for example. The DOM should be updated, and it seems like this is happening if you can show the changed value in an alert box. Commented Sep 6, 2011 at 14:55
  • Well, what do you suggest then, if I have a checkbox which have a value that I want to change when clicked? Commented Sep 6, 2011 at 15:01
  • @David: The value changes and is sent to the server, but the change is not reflected in the HTML (which is normal). Besides, only the value of selected checkboxes is sent to the server (if you use a normal POST request). Commented Sep 6, 2011 at 15:19

3 Answers 3

3

You need to use attr for it to be reflected in the HTML.

$("#box").attr("checked", "checked");

http://jsfiddle.net/Xeon06/BwGeX/

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

2 Comments

Nope, not working. At least not for me. The HTML value remains unchanged.
Well what do you mean by HTML value? The source code of the file will never be changed, but if you inspect the DOM, using a browser like Chrome, you'll see it will have changed.
1

<input id="box" type="checkbox" value=""> - the "value" represents the load time html that the browser renders.

Runtime value of the Form elements are not updated in DOM inspectors

A checkbox's "Checked" value is not related to the "Value" attribute, though it can be manipulated to reflect a different value.

You can obtain the checkbox value as $("#box").is(':checked'), this returns true/false

Comments

1

I had to use

$("#box").attr('value', '1');

in a recent project. For some reason, .val('1') wasn't working.

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.