0

I am adding options to the html select dynamically using jQuery at the same time I am setting the default value, but the default value is not shown.

Here is the bare html code initially.

<div class="form-group">
        <select id="f_id" class="form-control">
        </select> 
</div>

and jQuery code where I am adding the options dynamically

var $fTypeSelect = $('#f_id');
$.each(fVal, function(idx, obj){ 
        $fTypeSelect
        .append($("<option></option>").attr("value",obj["ftype_id"]).text(obj["fType"]));
});

So far it has added the options to drop down and it works.

I tried to set the default value in the following ways, none of them is showing as selected.

$fTypeSelect.val(fTypeDefaultVal);//Not shown as the default value
$fTypeSelect.val(fTypeDefaultVal).change();// Not shown as default value
$fTypeSelect.trigger("chosen:updated");//Default value is still not shown

My drop down in the UI is as shown below. enter image description here

When drop down is expanded all the options are found. How to set the default value? My jQuery version is 2.1.4.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
srk
  • 4,857
  • 12
  • 65
  • 109
  • 2
    `$('#f_id option[value=' + fTypeDefaultVal + ']').attr('selected', 'selected');` try – guradio Nov 11 '15 at 09:04
  • 1
    `$fTypeSelect.val(fTypeDefaultVal);` should work. Just check if there is an item with `value` equal to `fTypeDefaultVal` – Yeldar Kurmangaliyev Nov 11 '15 at 09:07
  • There is no such item whose value equal to fTypeDefaultVal. But hardcoding the existing value to test also doesn't work. $fTypeSelect.val("1"); – srk Nov 11 '15 at 09:16
  • what about duplicate id for select? – guradio Nov 11 '15 at 09:17
  • There is no duplicate id. – srk Nov 11 '15 at 09:18
  • 1
    Setting through val() function is working. See this plunker http://plnkr.co/edit/gist:1986619?p=preview. Refer this post: http://stackoverflow.com/questions/13343566/set-select-option-selected-by-value for more info – Ganesh Kumar Nov 11 '15 at 11:00
  • Messed up with my code, it is working val(). And all the help in comments are correct too. – srk Nov 11 '15 at 12:34

1 Answers1

0

Somewhere in the code I was setting the value for the select dropdown which doesn't exist, hence the issue.

Example:

<select id="f_id" class="form-control">
  <option value="1">example1</option>
</select> 

jQuery snippet

var $fTypeSelect = $('#f_id');
$fTypeSelect.val("1");// This is working
// After few lines of messy code I was setting the wrong value as in below
$fTypeSelect.val("string");// This is where I was wrong

Because of this it is not showing the option selected.

srk
  • 4,857
  • 12
  • 65
  • 109