0

I am trying to alert the text of a div which is in a for loop when it is clicked. There are many divs with same id, i want to get 3 if i click the 3rd or 2 when 2nd is clicked. How can i make it with the following code or what must i add to it? Thank you.

<? for($i=0; $i<5; $i­­++) { ?>
    <div id="abc"><? echo $i ?></div>
<? } ?>

<script>
    $(function() {
        $("#abc").click(function() {
            var thevar= $("#abc").text();
            alert (thevar);
        }
</script>
2
  • 1
    id should be unique..! :/ Commented Apr 23, 2014 at 8:15
  • You're missing a few closing brackets (); });) at the end of your script. Commented Apr 23, 2014 at 8:17

3 Answers 3

1

Just try to use a class instead of using id inside that loop,

<? for($i=0; $i<5; $i­­++) { ?> 
<div class="abc"><? echo $i ?></div>    
<? } ?>

<script>
$(function() {
   $(".abc").click(function() 
     {
       var thevar= $(this).text();
       alert (thevar);
     });
 });
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

You should have unique ids on page. due to this $("#abc").text() always returns value for first element in matched selector. Rather use abc as class. and to refer element in current context, use $(this):

 var thevar=$(this).text();

Comments

1

You have syntax error in your code. Missing }); . Id should be unique .

<? for($i = 0;$i<5;$i++) { ?>

<div class="abc"><? echo $i ?></div> //change

<? } ?>

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>



<script>
$(function() {
$(".abc").click(function() 
{
var thevar= $(this).text(); //change
alert (thevar);
});//was missing
});//was missing
</script>

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.