3

Here is the jsfiddle for what I was testing http://jsfiddle.net/5hhRF/

there is number 1 2 1 2.... when u click last digit which is "2" it don't alert.

Was I missing some code for that case?

I am copying the same code here again.

<span class="open-option" id="option1" >1</span>
<span class="open-option" id="option2" >2</span>

<span id="open-option" class="option1" >1</span>
<span id="open-option" class="option2" >2</span>​

    $(".open-option").click(function(){                    
       var myID=$(this).attr('id'); 
       alert(myID);
    });

    $("#open-option").click(function(){                    
       var myClass=$(this).attr('class'); 
       alert(myClass);
    });


                        ​
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
cjmling
  • 6,896
  • 10
  • 43
  • 79
  • Ok, Thank you for all the answer( which r mostly same ). I thought "(this)" can uniquely identify the clicked id. My fault assumption :( – cjmling Apr 06 '12 at 06:17

4 Answers4

3

You can't assign the same id to multiple elements.

http://htmlhelp.com/reference/html40/attrs.html

The ID attribute uniquely identifies an element within a document. No two elements can have the same ID value in a single document.

sberry
  • 128,281
  • 18
  • 138
  • 165
3

click event is binding only to first element with given id.

ID's in the page must be unique.

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
1

jQuery id selector return an array but contains only 1st elements in DOM with the id. So here in your code the click handler is being applied to 1st DOM elements only

you can make use of contains selector

$("span[id*='open-option']").click(function(){                    
   var myClass=$(this).attr('class');
   alert(myClass);
});

fiddle : http://jsfiddle.net/5hhRF/4/

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • Although I accepted the fact that ID should be unique so I will follow that. But thank you very much for the hacked code. Can u plz link me to the DOC for better understanding for the kind of selector u use. span[id^='. Thanks Again :D – cjmling Apr 06 '12 at 06:25
  • 1
    u should actully accept this answer because its not oly telling u the reason but also giving u the alternative solution lollzzz... anyway u r most welcome.. u can find it http://api.jquery.com/category/selectors/ – dku.rajkumar Apr 06 '12 at 06:26
0

Element IDs must be unique, I'm afraid, as per here. Otherwise, your code simply won't work.

Community
  • 1
  • 1
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123