views:

42

answers:

5

What I need to do is get the value of the selected option (when changed) in a select list and change the text in a span next to the select list. The problem is I don't know the id the the select list. There are lot of different select list on the page (5-25+) and they are all created dynamically and so I can't have the id specified in the .change(). Here is what I have:

JS:

$("select").change(function () {
   var str = "";
   str = $("select option:selected").text();

   $(".out").text(str);
}).trigger('change');

(Of course this doesn't work, puts all of the select values in each span)

HTML:

<select name="animal[]">
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="bird">bird</option>
<option value="snake">snake</option>
</select>
<span class="out"></span>

I feel like I am missing something simple but I can't find anything. Thanks for all of your help.

A: 

Sounds like you want to use jQuery's next

epascarello
It may work for adding the text to the span but won't help getting the select value.
Scott
+2  A: 

Try this:

$("select").each(function(){

    var select = $(this),
        out = select.next();

    select.change(function () {
        out.text(select.val());
    });

}).trigger('change');
J-P
http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event-using-jquery seems like, in event handlers "this" refers to source of the event.
yilmazhuseyin
+2  A: 

Try something like this:

$("select").change(function () {
   var txt = $(this).val();
   $(this).next('span.out').text(txt);
}).trigger('change');​
Ken Redler
A: 

You can get the changed element using $(this) w/in the event callback.

Try changing the line -

str = $("select option:selected").text();

To -

str = $(this).find("option:selected").text();
mld
A: 

How about this?

$("select").change(function () { 
   var str = ""; 
   str = $(this).find(":selected").text(); 

   $(".out").text(str); 
}).trigger('change'); 
Paul Hadfield