Search code examples
jqueryjquery-uijquery-ui-button

jquery, setting checkboxes to true on load


I have a setup like this...

$(document).ready(function(){ 
  var model = { /* some variable names */, Traits[] };
  var traits = // json array pulled from server.

  $('input[type=checkbox]').button(); // jquery ui button control.
});

Now, in my HTML, I have a jQuery Template like this.

{{each(i, trait) traits}}
   <input type='checkbox' id='chk${trait.Name}' />
   <label for='chk${trait.Name}'>${trait.Name}</label>
{{/each}}

Now, when I am creating things using this style, it works great. But when I go to edit things, I want the 'Traits' that have already been picked to be 'checked' by default. So I tried this code..

// jquery startup... variable loading, etc.
function evaluateCheckbox(item){
   $("'#chk" + item.Name + "'").attr('checked', true);
}
model.Traits.forEach(evaluateCheckbox);

Not only does this not check the boxes, but it then creates every checkbox twice. I don't understand why this is. Can anyone give me some insight, and an idea on how to fix it?


Solution

  • You have an extra set of qoutes in there, it should just be:

    $('#chk' + item.Name).attr('checked', true);
    

    You probably want to refresh the jQuery UI button's visible state afterwards as well, like this:

    $('#chk' + item.Name).attr('checked', true).button('refresh');