[javascript] How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

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

This question is related to javascript jquery html

The answer is


Here it goes.

_x000D_
_x000D_
// Select by value_x000D_
$('select[name="options"]').find('option[value="3"]').attr("selected",true);_x000D_
_x000D_
// Select by text_x000D_
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<select name="options">_x000D_
      <option value="1">First</option>_x000D_
      <option value="2">Second</option>_x000D_
      <option value="3">Third</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

Edit: Working example of my testing (the error:undefined is from jsbin, not my code).


Here is another way you can change the selected option of a <select> element in javascript. You can use

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

Here is a sample code. Check if you can use this type of approach:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

Your syntax is wrong.

You need to call attr with two parameters, like this:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected" to the variable defaultSelected, then passes that value to the attr function, which will then return the value of the selected attribute.


SCRIPT

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details


Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment