V Posted July 25, 2010 Share Posted July 25, 2010 After reading some Jquery documentation I tried to implement something for my site. If a link's "id" and "name" have equal values the background color of the link's class should change to green otherwise red. <script type="text/javascript"> $(function() { var ID = $(".color_test").attr("id"); var name = $(".color_test").attr("name"); if (ID==name) { $('.color_test').css({"background":"green"}); } if (ID!==name) { $('.color_test').css({"background":"red"}); } }); </script> The HTML is dynamic but I made a simple example <a href class="color_test" id="1" name="1">Should be green</a> <a href class="color_test" id="3" name="4">Should be red</a> <a href class="color_test" id="8" name="8">Should be green</a> and the css .color_test { display:block; padding:10px; } What happens is.. if "id" and "name" in the first link are equal, all the links become green even if some don't have equal values. :-\ And so if the first link doesn't have equal values they all become red. It seems that it's just picking up the data from the first link rather than each one individually. Can someone please help me out with this? Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted July 25, 2010 Share Posted July 25, 2010 You'll need to iterate through all elements with the class name of color_test <script type="text/javascript"> $(function() { $('.color_test').each(function(i) { if($(this).attr("id") == $(this).attr("name")) $(this).css({"background-color":"green"}); else $(this).css({"background-color":"red"}); }); }); </script> Quote Link to comment Share on other sites More sharing options...
V Posted July 25, 2010 Author Share Posted July 25, 2010 Brilliant! Thanks wildteen88! It's work perfectly now Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.