-4

I have this small problem

<ul>
    <li><span id="test">val1</span></li>
    <li><span id="test">val2</span></li>
    <li><span id="test">val3</span></li>
</ul>

But when I try to get the value of the clicked span I get the value of the first one only (when I click the second or third span I can't get the value of it ) I don't know why this is happening.

Here's the jquery code :

$(document).ready(function(){

   $("#test").click(function(){
         val = $(this).text();
         alert(val);
    });

});
Tolga Evcimen
  • 6,780
  • 10
  • 55
  • 87
HamIsm
  • 33
  • 5

2 Answers2

3

Id should be unique, use class instead of it.

<ul>
<li><span class="test">val1</span></li>
<li><span class="test">val2</span></li>
<li><span class="test">val3</span></li>
</ul>

js

$(document).ready(function(){

   $(".test").click(function(){
         val = $(this).text();
         alert(val);
    });

});

Demo

Anoop Joshi P
  • 24,863
  • 8
  • 29
  • 52
1

use class instaed of id . as id should be unique.

<ul>
<li><span class="test">val1</span></li>
<li><span class="test">val2</span></li>
<li><span class="test">val3</span></li>
</ul>

jquery

$(document).ready(function(){

   $(".test").click(function(){
         val = $(this).text();
         alert(val);
    });

});

Demo

Amit Kumar
  • 5,766
  • 10
  • 45
  • 80