ASWATHY
ASWATHY

Reputation: 55

How to Set the Default Value of a Dropdown List with Javascript

 <select class="form-control sprites-arrow-down" id="TaskFitToWork" name="TaskFitToWork" onchange="getInstructions();" >
     <option selected disabled value="">Select Fit To Work</option>
     {{range $key, $val := .vm.FitToWorkArray}}
           <option id="{{index $.vm.FitToWorkKey $key}}" value="{{$val}}" >{{$val}} </option>
     {{end}}
 </select>

This is my HTML code to fill a dropdown list using golang.

 var fitToWorkName = vm.FitToWorkName

document.getElementById("TaskFitToWork").value = fitToWorkName;

This is the JavaScript code . Note, that here vm.FitToWorkName contains value to be filled in the drop down list. I tried to set the default fill for the dropdown list but it is not working. Please help me solve this issue.

Upvotes: 0

Views: 13432

Answers (1)

slevy1
slevy1

Reputation: 3832

One may set the default value of a dropdown list with either HTML or JavaScript, as this example illustrates. Initially, the code sets the default option using HTML and later at the user's discretion the default can be reset with JavaScript. At the outset the critical part of the code involves applying "selected" to the desired default option. If the user chooses a different option, then clicking the button that restores the default option activates some JavaScript. A simple, one-liner function uses the select element's selectedIndex property and sets it to indicate the second option. Since the array of options use zero-based indexing that index has a value of one.

var d = document;
d.g = d.getElementById;
var btn = d.g("btn");
var mySelect = d.g("mySelect");



function getInstructions(){ 
   return true; 
}

function restoreDefault(){
  
   mySelect.selectedIndex = 1;
}

btn.onclick = restoreDefault;
option:first {
    background: #fff;
    color:#009;
}

select {
    background:#fff;
    color:#009;
}
<select id="mySelect" class="form-control sprites-arrow-down" id="TaskFitToWork" name="TaskFitToWork"  onchange="getInstructions();" value>
     <option id="val" value="" disabled>Select Fit To Work</option>
                <option id="val" value="somevalue" selected>Some Value </option>
                <option id="val" value="anothervalue" >Another Value </option>
                <option id="val" value="morevalue" >More Value </option>
     
 </select>
 
 
 
<button id="btn">Restore Default</button>

Upvotes: 1

Related Questions