SoFunction
Updated on 2025-03-08

JS method to set the currently selected value in the drop-down list box

This article describes the method of setting the currently selected value of the JS drop-down list box. Share it for your reference, as follows:

1. JS code:

function setSelectOption(objId, targetValue){
//objid: The ID of the drop-down list box; targetValue: The currently selected value var obj = (objId);
 if(obj){
  var options = ;
  if(options){
   var len = ;
   for(var i=0;i<len;i++){
    if(options[i].value == targetValue){
     options[i].defaultSelected = true;
     options[i].selected = true;
     return true;
    }
   }
  } else {
   alert('missing element(s)!');
  }
 } else {
  alert('missing element(s)!');
 }
}

2. Set the current selection item of the drop-down list box in JSP

<select>
  <option value="1" <%if(sesssionValue==1){%> selected="selected"<%}%>>1:b </option>
  <option value="2" <%if(sesssionValue==2){%> selected="selected"<%}%>>2:b </option>
  <option value="3" <%if(sesssionValue==3){%> selected="selected"<%}%>>3:c </option>
  <option value="4" <%if(sesssionValue==4){%> selected="selected"<%}%>>4:d </option>
</select>

I hope this article will be helpful to everyone's JavaScript programming.