简体   繁体   中英

JQuery Get selected value from dynamically generated dropdown

I have an Dropdown list which is generated dynamically

the below is the code snippet of the Dropdown generated

<select class='selectAggregate'>
  <option>Select</option>
  <option>Min</option>
  <option>All</option>
</select>

How can i get the Seleceted option using JQuery

Edit I added the jquery code I have used

 $('.selectAggregate').each(function()
            {
                var $val = $("option:selected",this).text();                    
        }   

selectAggregate is the class attribute of dynamically generated dropdowns

Based on assumptions that you are using "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

General Syntax

$(document).on('event','selector',callback_function)

Example

$(document).on('change', ".selectAggregate", function(){
    alert($(this).val())
});

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Try this

 $("button").click(function(){
        $.each($(".selectAggregate option:selected"), function(){            
           var $val = $(this).text();

        });
    });
$(document).on('change','.selectAggregate', function() {
var temp = $('.selectAggregate').children(":selected").text();
});

This will help you out, here you can get the value of dynamically generated select. the change event is used because the element inside select (option) is being generated dynamically.

要获得选择的值,您可以在js文件中使用以下语句。

$(".selectAggregate option:selected").val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM