0

I tried to entirely script this checkbox check / uncheck snippet of code in jQuery, but it did not have any success. Here is the jQuery/JavaScript code:

$.ajax({
                type: "GET",
                url: "check.xml",
                cache: false,
                dataType: "xml",
                success: function(xml) {
                    $(xml).find("check").each(function(){
                        $(xml).find("todo").each(function(){
                            var state = $(this).attr("state");
                            if (state == "true") {
                                document.getElementById($(this).attr("id")).checked = true;
                            } else {
                                document.getElementById($(this).attr("id")).checked = false;
                            }
                        });
                    });
                }
            });

It's probably very possible to do the document.getElementbyId(blablabla).... using only jQuery. I tried this:

($(this).attr("id")).prop("checked", true)

But that didn't really work as expected. Any suggestions?

maikovich
  • 368
  • 2
  • 3
  • 16

2 Answers2

1

You need to do it like this (note the # symbol to get a element from the ID - same rules than CSS selectors) -

var id = $(this).attr("id");
$('#'+ id).prop("checked", true);
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

You're missing the "#" in the selector:

var id = '#'+ $(this).attr("id");

Then you can do a one liner instead of the "if":

$(id).prop("checked", (state == "true"));
Wilmer
  • 2,511
  • 1
  • 14
  • 8