Punit Gajjar Punit Gajjar - 3 months ago 7
jQuery Question

Show option as selected in each loop

i am rendering all the option of the select box through an ajax call inside

$(document).ready();
function.

i have one php variable at the top of the page which is initialized with 1 like

$expert_id = 1;


Now here is my code

$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
}
});
});


while appending all the option to my expert select box i want to check if
data[i].expert_id
is equal to my php variable or not, if it is equal to my php variable then it should be selected.

anybody can help me with this ?

Answer

Use selected property/attribute while creating jQuery object(<option>)

Refer jQuery( html [, ownerDocument ] )

var data = [{
  expert_id: 1,
  expert_name: 'rayon'
}, {
  expert_id: 2,
  expert_name: 'bye'
}];
var expert_id = 2;
$.each(data, function(i, item) {
  $('#expert').append($('<option>', {
    value: data[i].expert_id,
    text: data[i].expert_name,
    selected: expert_id === data[i].expert_id
  }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="expert"></select>

Fiddle Demo