Mark Henry
Mark Henry

Reputation: 2699

Add a option to a selectbox list with jquery

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

Answers (1)

Jared Farrish
Jared Farrish

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);

http://jsfiddle.net/RhhAZ/1/

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>');

http://jsfiddle.net/RhhAZ/4/

Upvotes: 1

Related Questions