How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?
html, javascript, jquery
Solution
The `defaultSelected` attribute is not settable, it's just for informational purposes:
Quote:
The defaultSelected property returns the default value of the selected attribute. This property returns true if an option is selected by default, otherwise it returns false.
I think you want:
$('option[value=valueToSelect]', newOption).attr('selected', 'selected');
I.e. set the `selected` attribute of the `option` you want to select.
Without trying to fix your code, here's roughly how I would do it:
function buildSelect(options, default) {
// assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
// default = 'value1'
var $select = $('<select></select>');
var $option;
for (var val in options) {
$option = $('<option value="' + val + '">' + options[val] + '</option>');
if (val == default) {
$option.attr('selected', 'selected');
}
$select.append($option);
}
return $select;
}
You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.
Problem
For some reason, I can't get this to work. My options list is populated dynamically using these scripts: ``` function addOption(selectId, value, text, selected) { var html = '<option value="'+value+'">'+text+'</option>'; if (selected == "on") { html = '<option value="'+value+'" selected="selected">'+text+'</option>'; } $('#'+selectId).append(html); } function addSalespersonOption(id, name, defsales) { addOption('salesperson', id, name, defsales); } ``` Here is the HTML: ``` <td class="text-r"><label for="salesperson">Salesperson:</label></td> <td> <select id="salesperson"> <option value="">(select)</option> </select> </td> ``` So far, the output is: ``` <option value="1266852143634" selected="selected">Eric Hunt</option> ``` The DOM shows this: ``` index 2 disabled false value "1266852143634" text "Eric Hunt" selected false defaultSelected true ``` But for some reason, when the page is loaded, the dropdown does not display Eric Hunt as pre selected. Nor is anything for that matter. How can I get "selected true" instead of "defaultSelected true"? EDIT: As it turns out, the above code works perfectly, thanks to the help of deceze and rosscj2533's answers from below. The only reason it's not working for me is, I found Ruby code that was overwriting the select elements. Thanks for everyone's help on this, Cheers