Adding checked attribute via jQuery

Chris picture Chris · Sep 14, 2010 · Viewed 43.3k times · Source

I am using the following widget http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/ It has worked great so far, but I need some help in adding attributes. In using Firebug, I've noticed that by simply clicking on the checkbox the checked attribute does not appear as I would expect it to. In my code, I've modified the widget, I've been able to add code to remove the attribute of checked.

this.removeAttribute(\'checked\'); this.checked=false;

if the item was checked beforehand. I've been successful in using this code

this.setAttribute(\'checked\', \'checked\'); this.checked=true; 

if the item was unchecked when the page loads.

My problem is coming when I need to be able to utilize both sets of code on the checkbox, I've attempted the following

onclick="if($(this).attr(\'checked\') == \'true\') { this.setAttribute(\'checked\', \'checked\'); this.checked=true; } else { this.removeAttribute(\'checked\'); this.checked=false; }

the code will remove the attribute of checked (if checked before hand on page load), but when I attempt to click on the checkbox to add the attribute (if not checked on page load), nothing happens.

Thanks for any help, and sorry for my poor coding.

Answer

Deviprasad Das picture Deviprasad Das · Sep 14, 2010

In jQuery for removing an attribute use

this.removeAttr('checked');

and for setting an attribute use

this.attr('checked', 'checked');