Sumon Bappi
Sumon Bappi

Reputation: 2019

How to select first option in a select box after appending options by jQuery

I have a select box in a modal where I am appending options using jQuery. I want the first option to be selected after appending all item. I have tried some but no luck. Here are my attempts below.

My select box in modal:

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

My jQuery code where appending and trying to set selected first option:

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

Upvotes: 2

Views: 1443

Answers (2)

D. Mike
D. Mike

Reputation: 1

Can you try:

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

Upvotes: 0

ScanQR
ScanQR

Reputation: 3820

Simply do this,

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

Upvotes: 3

Related Questions