Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery refresh select box

I am populating a select field using JQuery on page load using this method

 $('#select').append('<option value="' + result + '">' + result + '</option>'); 

However this leaves the select box 'blank', i.e the first value in the options list is not preselected as the selected option.

How do I 'refresh' this list so that the first value is preselected?

like image 636
user1202278 Avatar asked Feb 21 '12 15:02

user1202278


3 Answers

You can add a "selected" attribute to the option element you'd like to be selected:

$('#select')
    .append('<option value="' + result + '" selected="selected">' + result + '</option>'); 

You don't specify how you populate exactly you select element, using a loop, you could do like this:

var data = ['a', 'b', 'c'];
var $select = $('#select'); // you might wanna empty it first with .empty()

for (var i = 0; i < data.length; i++) {
    var o = $('<option/>', { value: data[i] })
        .text(data[i])
        .prop('selected', i == 0);
    o.appendTo($select);
}​

DEMO


So it seems you are using jQuery Mobile like you said in the comment.

If you are using the selectmenu widget, you need to programmatically refresh after you make programmatic change to its content/structure:

$select.selectmenu("refresh", true);

Documentation

like image 61
Didier Ghys Avatar answered Nov 07 '22 06:11

Didier Ghys


You may use

$('#select').removeAttr('selected').find('option:first').attr('selected', 'selected');
like image 5
Mohora Bogdan Avatar answered Nov 07 '22 04:11

Mohora Bogdan


Simply .. you set the value whatever you want , i.e : $('#select').val(5); .. so in your case its $('#select').val(result);

Edit : a full working example included :

<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.4.js'></script>
<select id='select'></select>
<br>
<input type=button onclick='addNew()' value='Add'>

<script>
function addNew()
{
        var result = Math.floor(Math.random()*1000);
        $('#select').append('<option value="' + result + '">' + result + '</option>'); 
        $('#select').val(result);           
} 
</script>

like image 4
Ashraf Avatar answered Nov 07 '22 06:11

Ashraf