Reputation: 3854
The options below are added dynamically by an ajax call. Now I want to get the selected value and use it further.
<select class="form-control" name="product" id="product">
<option value="1" selected="selected">sku_MOTOE</option>//added dynamically
<option value="2">sku_C</option>//added dynamically
<option value="3">sku_S2</option>//added dynamically
<option value="4">sku_S5</option>//added dynamically
</select>
jquery:
$(function() {
$("#product").load("/bin/getcontent?type=options");
console.log($("#product option:selected").val());//null
});
Upvotes: 0
Views: 358
Reputation: 28611
You need to wait for the load to complete:
$(function() {
$("#product").load("/bin/getcontent?type=options", function() {
console.log($("#product option:selected").val());
});
});
load is asynchronous so the next line of code (console.log) runs before the load has finished loading the options.
You can pass a function/callback to the "complete" parameter of load and that will be called when the load has finished loading.
Upvotes: 1
Reputation: 133403
Note, .load()
is an asynchronous function call. Statements following the .load()
method are execute immediately thus you are getting null
You need to use .load()
's complete callback method
A callback function that is executed when the request completes.
Script
$("#product").load("/bin/getcontent?type=options", function(){
console.log($("#product option:selected").val());
//Or, console.log($("#product").val());
});
Upvotes: 2