Catfish
Catfish

Reputation: 19284

jquery .each function

If I have 5 input boxes with the class .inputBox my jquery function adds these tags 5 times after each of the .inputBox lines. Why is that?

I just want each of these tags inserted once after each .inputBox.

Anyone know how to do that?

function addImages() {          

     $(".inputBox").each(function() {

          $('.inputBox').after("<img src=\"Images/thumbs_up_48.png\" class=\"thumbV\" id=\"up\" />");
          $('.inputBox').after("<img src=\"Images/thumbs_down_48.png\" class=\"thumbV\" id=\"down\" />");
    });
}

the html

<label for="FirstName">First Name</label>
<input type="text" class="inputBox" name="FirstName" title="First Name Here" id="firstName" />

Upvotes: 2

Views: 157

Answers (3)

psychotik
psychotik

Reputation: 39019

You probably don't need the each, do you? Based on your code and fix proposed by patrick, i think you can just use your original code without the each() call.

Upvotes: 0

Vinodh Ramasubramanian
Vinodh Ramasubramanian

Reputation: 3185

You can simply lose the each and just use

 $('.inputBox').after("<img src=\"Images/thumbs_up_48.png\" class=\"thumbV\" id=\"up\" />");
 $('.inputBox').after("<img src=\"Images/thumbs_down_48.png\" class=\"thumbV\" id=\"down\" />");

Upvotes: 0

user113716
user113716

Reputation: 322462

Use:

$(this).after("<img src=\"Images/thumbs_up_48.png\" class=\"thumbV\" id=\"up\" />");
$(this).after("<img src=\"Images/thumbs_down_48.png\" class=\"thumbV\" id=\"down\" />");

$('.inputBox') will iterate through the entire DOM every time you call it.

An even better way would be

$(".inputBox")
        .after("<img src=\"Images/thumbs_up_48.png\" class=\"thumbV\" id=\"up\" />")
        .after("<img src=\"Images/thumbs_down_48.png\" class=\"thumbV\" id=\"down\" />");

And don't forget to 'accept' an answer that works for you.

Upvotes: 1

Related Questions