Reputation: 2699
I use this jquery function to populate a dropdown box. Works great, but I want to add an option:
<option value="">select</option>
the first option! How is this to be done?
function populate_cantons() {
$.getJSON('http://domain.com/v3/ajax/fetch_canton.php', {country:$('#country').val()}, function(data) {
var select = $('#cantons');
var options = select.prop('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['canton']);
});
});
}
Upvotes: 0
Views: 1294
Reputation: 49188
<select id="cantons">
<option>This is 1</option>
<option>This is 2</option>
<option>This is 3</option>
</select>
var select = $('#cantons');
select.find('option:eq(0)').next().attr('selected', true);
Note, I'm using .next()
to show it works. It will select the first option
without it. Usually, the first option
in a select
will be selected if no other one is.
EDIT
var select = $('#cantons');
select.prepend('<option selected>Select</option>');
Upvotes: 1