Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?
    primarykey
    data
    text
    <p>For some reason, I can't get this to work. </p> <p>My options list is populated dynamically using these scripts:</p> <pre><code>function addOption(selectId, value, text, selected) { var html = '&lt;option value="'+value+'"&gt;'+text+'&lt;/option&gt;'; if (selected == "on") { html = '&lt;option value="'+value+'" selected="selected"&gt;'+text+'&lt;/option&gt;'; } $('#'+selectId).append(html); } function addSalespersonOption(id, name, defsales) { addOption('salesperson', id, name, defsales); } </code></pre> <p>Here is the HTML:</p> <pre><code>&lt;td class="text-r"&gt;&lt;label for="salesperson"&gt;Salesperson:&lt;/label&gt;&lt;/td&gt; &lt;td&gt; &lt;select id="salesperson"&gt; &lt;option value=""&gt;(select)&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; </code></pre> <p>So far, the output is:</p> <pre><code>&lt;option value="1266852143634" selected="selected"&gt;Eric Hunt&lt;/option&gt; </code></pre> <p>The DOM shows this:</p> <pre><code>index 2 disabled false value "1266852143634" text "Eric Hunt" selected false defaultSelected true </code></pre> <p>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.</p> <p>How can I get "selected true" instead of "defaultSelected true"?</p> <hr> <p>EDIT: As it turns out, the above code works perfectly, thanks to the help of <a href="https://stackoverflow.com/users/476/deceze">deceze</a> and <a href="https://stackoverflow.com/users/225085/rosscj2533">rosscj2533</a>'s answers from below. The only reason it's not working for me is, I found Ruby code that was overwriting the select elements.</p> <p>Thanks for everyone's help on this,</p> <p>Cheers</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload