1

I am trying to identify an attribute within each object of an array of checked boxes, but this code returns the desired element of only the attribute of the first object in the array for the number of boxes that I have checked. Here is my code:

function() {
    var checkedBoxes = $("[name='select-services']:checked");
    checkedBoxes.each(function(){
        console.log(checkedBoxes.attr("value"))
    }

For example, if the values of three selected boxes are "value 1", "value 2", and "value 3", I will receive the output "value 1" three times.

1
  • Refer to this inside the each to get to the item being iterated over. (or use the second argument) Commented Oct 19, 2018 at 7:17

2 Answers 2

1

Like the description of attr() says:

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

What you're doing now is getting the attr of the first item in checkedBoxes. But what you want is to get the value of the item you're currently iterating over. You can do that using $(this) in the function like in the example below.

checkedBoxes.each(function(){
    console.log($(this).attr("value"))
}
Sign up to request clarification or add additional context in comments.

Comments

0

The following code assigns an obj reference to each iteration of array and uses its attribute. The issue is you are querying checkedBoxes everytime in the loop.

function() {
    var checkedBoxes = $("[name='select-services']:checked");
    checkedBoxes.each(function(index, obj){
        console.log(obj.attr("value"))
    }

2 Comments

The first argument to each is the index, not the element. Use this instead, or use the second argument, not the first.
Corrected. The second argument is the value. I have a healthy disrespect for this in javascript and try to avoid it as much as possible.

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.