Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get changed select value

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?

like image 354
Scott Avatar asked Aug 13 '10 14:08

Scott


People also ask

How do I add dynamic options to select?

Add Options Dynamically To Select Element Inside the loop, create an option element and store in the variable called option. Then, set a value attribute to the option element and assign its value to the value of the property from the countriesData object on each iteration.

How to set option value in JavaScript dynamically?

It removes all first, and then adds the new ones: var optionsAsString = ""; for(var i = 0; i < productArray. length; i++) { optionsAsString += "<option value='" + productArray[i] + "'>" + productArray[i] + "</option>"; } $("select[name='inptProduct']").


2 Answers

Try something like this:

$("select").change(function () {
   var txt = $(this).val();
   $(this).next('span.out').text(txt);
}).trigger('change');​
like image 197
Ken Redler Avatar answered Sep 28 '22 05:09

Ken Redler


Try this:

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

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

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

}).trigger('change');
like image 20
James Avatar answered Sep 28 '22 04:09

James