7

I need to 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 of the select list. There are a lot of different select lists 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:

JavaScript:

$("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>

What am I missing?

Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
Scott
  • 3,290
  • 4
  • 29
  • 48

5 Answers5

16

Try something like this:

$("select").change(function () {
   var txt = $(this).val();
   $(this).next('span.out').text(txt);
}).trigger('change');​
Ken Redler
  • 23,863
  • 8
  • 57
  • 69
3

Try this:

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

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

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

}).trigger('change');
James
  • 109,676
  • 31
  • 162
  • 175
  • 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 Aug 13 '10 at 14:52
1

Try this:

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

   $(".out").text(str); 
}).trigger('change'); 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Hadfield
  • 6,088
  • 2
  • 35
  • 56
0

Sounds like you want to use jQuery's next

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You can get the changed element using $(this) within the event callback. Try changing the line

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

to

str = $(this).find("option:selected").text();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mld
  • 519
  • 6
  • 15