簡體   English   中英

通過jQuery附加選項后如何在選擇框中選擇第一個選項

[英]How to select first option in a select box after appending options by jquery

我在模態中有一個選擇框,在其中使用jquery附加選項。 我希望在附加所有項目后選擇第一個選項。 我嘗試了一些但沒有運氣。 誰能幫我這個忙嗎? 這是我在下面的嘗試:

我的模態選擇框>>>

<select id="modal_cmbSection" name="modal_cmbSection" class="form-control required">
</select>

我的jQuery代碼,其中追加並嘗試設置所選的第一個選項>>>

var sectionOption = "";
var $sectionSelect = $('#modal_cmbSection');
$sectionSelect.empty();
$(".section-block").each(function() {
    var eachSectionName = $(this).find(".section-section-name").val();
    sectionOption = "<option>" + eachSectionName + "</option>";
    $sectionSelect.append(sectionOption);
});
$sectionSelect.find('option:eq(0)').prop('selected', true);

簡單地做到這一點,

var sectionOption = "";
var $sectionSelect = $('#modal_cmbSection');
$sectionSelect.empty();
$(".section-block").each(function() {
    var eachSectionName = $(this).find(".section-section-name").val();
    sectionOption = "<option>" + eachSectionName + "</option>";
    $sectionSelect.append(sectionOption);
});
//set selected as true for first option
$("#modal_cmbSection option:first-child").attr("selected", true);

你能試一下嗎:

$sectionSelect.find( 'option:first' ).prop( 'selected', true );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM