-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
  • 7,112
  • 11
  • 58
  • 91
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
  • 25,373
  • 8
  • 32
  • 53
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,888
  • 11
  • 47
  • 85