0

I have the following loop using the jQuery each method. I'm trying to leverage the index of the loop to ensure checkboxes and labels in my markup have the correct dynamic content. On each pass through, I'm appending the index to the class name then assigning a value and text content to the appropriate elements, based on the new modified class name. Is there a simpler or cleaner way to go about this? 'Managers' in this case contains text and value properties for the items I'm iterating through.

$(Managers).each(function (index) {
    $('.chk-hr').attr('class', 'chk-hr-' + index);
    $('.chk-hr-' + index).attr("value", this.Text);
    $('.lbl-hr').attr('class', 'lbl-hr-' + index);     
    $('.lbl-hr-' + index).text(this.Text);
});

Desired output:

<input class="chk-hr-0" value="Bob">
<span class="lbl-hr-0">Bob</span>
<input class="chk-hr-1" value="John">
<span class="lbl-hr-1">John</span>
3
  • desired output added to original post Commented Dec 5, 2017 at 17:48
  • 1
    You could use .eq. Commented Dec 5, 2017 at 18:09
  • @ClaytonLeis thanks, exactly what I was looking for Commented Dec 5, 2017 at 19:47

1 Answer 1

1

As suggested by @ClaytonLeis, .eq helped me simplify this loop:

$(Managers).each(function (index) {
    $('.chk-hr').eq(index).attr("value", this.Text);
    $('.lbl-hr').eq(index).text(this.Text);
});
Sign up to request clarification or add additional context in comments.

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.