I'm trying to add 'checked' attribute to HTML string, which contains multiple HTML tags.
let someBtn = `<div class='btn'><input type='checkbox' id='${item.Id}'
value='Some value' class='active-btn'> <label class='btn'
for='${item.id}'></label></div>`;```
Doing it this way:
var something = $($.parseHTML(someBtn)).find('input[type=checkbox]').attr('checked', 1).prop('outerHTML');
returns only the tag, not the whole updated HTML string. Also that input tag gets checked="checked"
attribute instead of just checked
. Why is that? I cannot use attr('checked', true)
- there's no method with this kind of parameters.
Could somebody please help me out with this problem - to return the whole HTML string with proper checked attribute?
Useless to do $($.parseHTML('html_string'))
, you can directly use $('html_string')
.
You also need to seperate the fact to update your checkbox attributes and the fact to get the HTML.
const someBtn = `<div class='btn'><input type='checkbox' id='myId' value='Some value' class='active-btn'> <label class='btn' for='myId'></label></div>`; let html = $(someBtn); html.find('input').attr('checked', 1); html = html.prop('outerHTML'); // or html[0].outerHTML console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.