3

JSON data looks like this:

{"id":8,"userName":"gentelman","fullname":"Alexen","email":"[email protected]",
"mobile":"0060111434325","designation":null,"add_content":1,"edit_content":1,
"delete_content":1,"manage_user":1,"view_log":1}

I am trying to make checkbox checked when add_content = 1, else make it unchecked. Now it works only when I refresh page. I want to make it work without refreshing page. How to do that?

load: function (id) {
    var self = this;

    KeyWord.byId(
        id,
        function (data) {
            if (data.add_content == 1) {
                $("#add_content").attr('checked', true);
            } else {
                $("#add_content").attr('checked', false);
            }
            self.formHandler.load(data);
        },
        function (error) { },
        function () { }
    );
}
7
  • So you want the checking function to be bound to some event? When else does the value of add_content change besides on page refresh? Commented Nov 26, 2015 at 1:15
  • this load function reads data first and when add_content= 1 make checkbox checked without refreshing page .now checkbox is working but after I refresh the page Commented Nov 26, 2015 at 1:19
  • Have you tried using prop in place of attr here? Commented Nov 26, 2015 at 1:24
  • yeah...it did not work Commented Nov 26, 2015 at 1:25
  • have you tried specific comparison? your json is returning 1, but that no necessarily may be a bool valid comparison in Jquery. What if you place your condition like if (data.add_content == 1) ... since it may be considered as int instead of bool Commented Nov 26, 2015 at 1:39

3 Answers 3

2

You can do it in one line, just make sure you use .prop()

$("#add_content").prop('checked', data.add_content == 1);
Sign up to request clarification or add additional context in comments.

Comments

1

Change this code :

    if (data.add_content == 1) {
        $("#add_content").prop('checked', true); 
    } else {
        $("#add_content").prop('checked', false); 
    }
    self.formHandler.load(data);

To this :

    if (data.add_content == 1) {
        $("#add_content").attr("checked", "checked").closet(span).addClass("checked"); 
    } 
    self.formHandler.load(data);

Comments

0

yes you need to use prop() Setting a boolean attribute with jquery

http://api.jquery.com/prop/

load: function (id) {
var self = this;

KeyWord.byId(
    id,
    function (data) {
        if (data.add_content == 1) {
            $("#add_content").prop('checked', true); 
        } else {
            $("#add_content").prop('checked', false); 
        }
        self.formHandler.load(data);
    },
    function (error) { },
    function () { }
    );
}

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.