1

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!

2

2 Answers 2

2

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:

  • Use .prop('checked') instead of .attr('checked')
  • Even simpler, use this.checked, where this refers to the checkbox element itself

Solution 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;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.