2011-12-18 18 views
0

このjquery関数を使用してドロップダウンボックスを設定します。素晴らしいですが、 にオプションを追加します:jqueryを使用して選択ボックスリストにオプションを追加する

<option value="">select</option> 

最初のオプション!これはどのようにして行われますか?

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

答えて

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/

注、私はそれが動作を示すために.next()を使用しています。最初にoptionが選択されます。通常、最初のoptionselectであり、それ以外の場合は選択されません。

EDIT

var select = $('#cantons'); 
select.prepend('<option selected>Select</option>'); 

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

+0

私はオプションで先頭に追加します。既存のオプションに選択を設定しない。 – mark

+0

@mark - 私の編集を参照してください。 –

+0

@mark - あなたのマークアップのいくつかが質問に表示されていないことを知った後、私はもう一度編集しました。 –

関連する問題