Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  10] [ 6]  / answers: 1 / hits: 180685  / 14 Years ago, wed, august 4, 2010, 12:00:00

I've been trying to figure out how to add the attribute checked to a checkbox on click. The reason I want to do this is so if I check off a checkbox; I can have my local storage save that as the html so when the page refreshes it notices the checkbox is checked. As of right now if I check it off, it fades the parent, but if I save and reload it stays faded but the checkbox is unchecked.



I've tried doing $(this).attr('checked'); but it does not seem to want to add checked.



EDIT:
After reading comments it seems i wasn't being clear.
My default input tag is:



<input type=checkbox class=done>


I need it top be so when I click the checkbox, it adds checked to the end of that. Ex:



<input type=checkbox class=done checked>


I need it to do this so when I save the html to local storage, when it loads, it renders the checkbox as checked.



$(.done).live(click, function(){
if($(this).parent().find('.editor').is(':visible') ) {
var editvar = $(this).parent().find('input[name=tester]').val();
$(this).parent().find('.editor').fadeOut('slow');
$(this).parent().find('.content').text(editvar);
$(this).parent().find('.content').fadeIn('slow');
}
if ($(this).is(':checked')) {
$(this).parent().fadeTo('slow', 0.5);
$(this).attr('checked'); //This line
}else{

$(this).parent().fadeTo('slow', 1);
$(this).removeAttr('checked');
}
});

More From » jquery

 Answers
58

It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr() method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]



IE has some problems with the DOM setAttribute method but in this case it should be fine:



this.setAttribute(checked, checked);


In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked attribute, you need to set the checked property as well:



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


To uncheck the checkbox and remove the attribute, do the following:



this.setAttribute(checked, ); // For IE
this.removeAttribute(checked); // For other browsers
this.checked = false;

[#96024] Monday, August 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadon

Total Points: 488
Total Questions: 105
Total Answers: 105

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
;