Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  39] [ 3]  / answers: 1 / hits: 16480  / 10 Years ago, thu, february 19, 2015, 12:00:00

So I have no problem actually setting checkboxes as checked, however in my current case I need to actually add the checked property to the checkboxes, as the system I'm working in literally grabs the HTML from the DOM.



I can set the checkbox to be checked, however as there's no identifying checked property when the HTML gets inserted again it doesn't hold the property so all checkboxes come back unchecked :(



is there a way to add and remove 'checked' as a property so it will be apparent from the raw HTML what boxes are checked? e.g.



unchecked box



<input type=checkbox value=yes />


checked box



<input type=checkbox checked value=yes />


Appreciate any help!!


More From » jquery

 Answers
39

I'm pulling RAW html from the page, but by default it seems checked checkboxes don't have any identifying properties or attributes so the HTML that is extracted doesn't know if they were checked or not, if I can add or remove the checked property it will solve my problem.




That's correct, the checked state isn't reflected in the markup you get back from innerHTML for the element.



You can force it to be by explicitly setting and removing the attribute on the element; below is an example doing it when the checkbox is clicked, or alternately you might do it by updating the elements immediately before grabbing their HTML.



This works on Chrome, Firefox, IE11, and IE8, for instance:





$(input).on(click, function() {
if (this.checked) {
this.setAttribute(checked, checked);
} else {
this.removeAttribute(checked);
}
snippet.log(this.parentNode.innerHTML);
});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<div>
<input type=checkbox value=yes>
</div>
<!-- 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>





Note I had to go straight to the DOM to do it, as jQuery has special handling in attr for checked.


[#67761] Tuesday, February 17, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juand

Total Points: 366
Total Questions: 95
Total Answers: 90

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;