0

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']);
        });
    });
}
0

1 Answer 1

1
<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/

Sign up to request clarification or add additional context in comments.

2 Comments

I want to prepend on option. Not set the selection on an existing option.
@mark - I edited it again after I realized some of your markup wasn't displaying in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.