Semantic UI: How to define selected item of search dropdown ("<select>")?

Anton picture Anton · Jun 10, 2015 · Viewed 42.5k times · Source

how can I set the selected item of a search dropdown (select) form field? I tried it with the following jQuery/JavaScript code:

if (equal == 0) {
    $('#sj_company').html($('#sj_company').html() + '<option value="' + key + '" selected="selected">' + data[key] + '</option>');
    $('.searchdropdown').dropdown('set selected', data[key]);
} else {
    $('#sj_company').html($('#sj_company').html() + '<option value="' + key + '">' + data[key] + '</option>');
}

Edit: The base is the semantic ui frontend framework ;-)

Answer

Cymen picture Cymen · Jun 10, 2015

For the Semantic UI framework, you should consult the guide here: dropdown behavior. That tells us to make the following call:

$('#dropdown').dropdown('set selected', value);

Or pass an object (perhaps useful for multiple select or to the developer's preference):

$('#dropdown').dropdown({'set selected': value});

Non-framework answer (before question was edited for specific framework)

If the select list has an id of say dropdown, you can do:

$('#dropdown').val();

To set the value, say the option has a value of a, you can do:

$('#dropdown').val('a');

I suggest reading the jQuery page on .val().

JSFiddle example: http://jsfiddle.net/vo9kpsry/1