Punit Gajjar Punit Gajjar - 1 year ago 57
jQuery Question

Show option as selected in each loop

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


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

type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
$('#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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download