I have a list of inputs of type checkbox in HTML, and JS uses an array variable to mark some of them as checked, like this:
profileData.interests.forEach(interest => {
$(`#profile-interests input#${interest}`).attr("checked", true)
})
Then the user is free to check / uncheck any inputs, and once he's done, he can click save, and I need to get the list of currently checked inputs (their IDs) and put them in a variable.
If I use this code, the list of inputs will be the initial one (from the initial variable):
$("#profile-interests input").each(function() {
if ($(this).attr('checked')) {
newInterests.push($(this).attr('id'))
}
})
If I use this code, the list of inputs is correct and corresponds to what I see on the page:
$("#profile-interests input:checked").each(function() {
newInterests.push($(this).attr('id'))
})
What's wrong with the first option?
Thanks!
That is because .attr()
and .prop()
returns different things. .prop()
should be used to check for the value of boolean properties/attributes, like checked
, readonly
, disabled
and etc.
On the other hand, $("#profile-interests input:checked")
contains the CSS :checked
pseudo-selector that will match checked elements properly and does not rely on the mechanism used in .attr()
(basically, functionally identical to using .prop()
.
There are two solutions:
.prop('checked')
instead of .attr('checked')
this.checked
, where this refers to the checkbox element itselfSolution 1: Use .prop()
:
$("#profile-interests input").each(function() {
if ($(this).prop('checked')) {
newInterests.push($(this).attr('id'))
}
});
Solution 2: Use native checked
property:
$("#profile-interests input").each(function() {
if (this.checked) {
newInterests.push($(this).attr('id'))
}
});
On a similar note, you should avoid using .attr()
to toggle the checked
property. Use .prop
instead:
profileData.interests.forEach(interest => {
// Option 1:
$(`#profile-interests input#${interest}`).prop("checked", true)
// Option 2:
$(`#profile-interests input#${interest}`)[0].checked = true;
});
attr() and prop() dont return the same thing:
.attr('checked'); // "checked"
// new property method
.prop('checked'); // true
its better to use.prop, you'll have always boolean
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.