jquery - Javascript improving ajax call for populating select -


i using code data , populate 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 need after populating select value of 1st line populated in select.

how can this?

to can set val() of select first item in 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 want force selection first option within select can set selectedindex property 0:

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

also note amended loop generate single html string appended dom once, quicker amending dom on each iteration.

update

i want value of first 1 , store in variable can use later

in case can use result.main[0].id:

var first = result.main[0].id 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -