user6552641
user6552641

Reputation:

Javascript improving ajax call for populating select

I am using this code to get some data and populate a select dropdown.

$.ajax({
    url: 'myurl here',
    method: 'GET',
    success: function(result) {
        $.each(result.main, function(result, value) {
            $('#myselect').append($('<option>').text(value.id).attr('value', value.id));
        });
    }
});

What I need to do after populating the select is to get the value of the 1st line populated in the select.

How can I do this?

Upvotes: 1

Views: 28

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

To do this you can set the val() of the select to the first item in the array. Try this:

success: function(result) {
    var html = '';
    $.each(result.main, function(result, value) {
        html += '<option value="' + value.id + '">' + value.id + '</option>'
    });
    $('#myselect').append(html).val(result.main[0].id);
}

Working example

Alternatively if you want to force the selection to the first option within the select you can set the selectedIndex property to 0:

$('#myselect').append(html).prop('selectedIndex', 0);

Also note that I amended the loop to generate a single HTML string which is only appended to the DOM once, which is quicker than amending the DOM on each iteration.

Update

I want to get the value of the first one and store it in a variable so I can use it later

In that case you can use result.main[0].id:

var first = result.main[0].id

Upvotes: 1

Related Questions