Calipso
Calipso

Reputation: 967

JQuery Options added from js but selected value is not working

I am adding the options of a select item dynamically.

I added under

$( document ).ready(function() {

the following code

$options = '<option name="en" value="en" SELECTED>English</option><option name="de" value="de">German</option>';

$("#select_language").html($options);

when I refresh the page, the options can can be seen in my drop down menu. The problem is, the selected value is not comming as default value. What should I do?

Upvotes: 0

Views: 57

Answers (2)

Calipso
Calipso

Reputation: 967

I found the solution. jQueryMobile was expecting to refresh the select menu with

$("#select_language").selectmenu("refresh",true);

the final working code is as bellow.

 var $options = '<option name="en" value="en"
 selected="selected">English</option><option name="de"
 value="de">German</option>';

 $("#select_language").append($options);

 if($('#select_language option:selected').length > 0 ) {


var selected = $('#select_language').val();
     alert(selected); 

} else {


     alert('nothing selected'); 
}

 $("#select_language").selectmenu("refresh",true);

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34406

Have a look at this - http://jsfiddle.net/stG89/1/

if($('#select_language option').prop('selected')) {
    var selected = $('#select_language').val(); 
    console.log(selected); // should log 'en' in this case
} else {
    console.log('nothing selected');
}

Upvotes: 1

Related Questions