nyshangal
nyshangal

Reputation: 102

how to access a tags with the same classname and handle onClick using javascript?

I have two select dropdown with same classname, I will like to return the title when option value is selected. however with the code I have, when a second dropdown is changed, it still returns the value selected in first option dropdown

http://jsfiddle.net/kgrg/ETeZe/3/

Upvotes: 1

Views: 96

Answers (3)

Fresheyeball
Fresheyeball

Reputation: 30015

You just need to use $(this) to refer to the select box that has changed, instead of just using a new selection (which will grab all).

http://jsfiddle.net/ETeZe/10/

Upvotes: 0

Ken Browning
Ken Browning

Reputation: 29091

The code you're using to pull out the value:

size_title=jQuery('.child_Select_Size  option:selected').attr("title");

Is matching all .child_Select_Size elements. To limit to just the one which triggered the event, try:

size_title=jQuery('option:selected', this).attr("title");

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69905

Because inside the change handler jQuery('.child_Select_Size option:selected') will select both the elements selected option and calling attr('title') on these matched elements will always give the title of the first element.

You should make use of this keyword which points to the element which raised the event. $(this).find will only look inside the element which raised the event. Also make use $ instead of jQuery if there is no conflict or use jQuery.noConflict()

$('.child_Select_Size').change(function(elmt){
    alert($(this).find('option:selected').attr("title"));
});

Demo

Upvotes: 0

Related Questions