简体   繁体   中英

add attribute to checkbox “checked ” with toggle

I am not much familiar with javascript or jQuery. I want to actually add and remove the checked attribute on a checkbox when its value changes, so that the attribute is included if we get the HTML of the checkbox (we store this HTML and want the state to be stored). Here's what I've tried:

$(document).on('click','.mark-as-done',function()
{
    if($(this).prop("checked"))
    {
        $(this).removeAttr('checked');
    }
    $(this).attr('checked','checked');
});

HTML:

<input type="checkbox" name="task" class="mark-as-done" style=" float: left;margin-top: 13px;">

jQuery has special handling around the attributes with reflected properties (like checked ), so you need to go straight to the DOM to do this. Also, your logic was always adding the attribute (because you didn't use else or return when removing it).

But it's just as easy with the DOM:

 $(document).on("click", ".mark-as-done", function() { // Actually add/remove the attribute, so that it's in the serialized // form when we store it (the `value` *property* isn't included when // serializing, so we do the attribute) if (this.checked) { this.setAttribute("checked", "checked"); } else { this.removeAttribute("checked"); } snippet.log(this.outerHTML); }); 
 <input type="checkbox" class="mark-as-done"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

Tested on Chrome, Firefox, IE9, and IE11.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM