Detailed explanation of how to set the default selected options for the . This method can control the output results as needed in the background in dynamic languages ​​such as php.

< select  id =  "sel" >
< option  value = "1" >1</ option >
< option  value = "2"  selected = "selected" >2</ option >
< option  value = "3" >3</ option >
</ select >
Copy after login


The second method is to control the selected item through front-end js:

< script  type = "text/javascript" >
function change(){
     document.getElementById("sel")[2].selected=true;
}
</ script >
< select  id =  "sel" >
< option  value = "1" >1</ option >
< option  value = "2" >2</ option >
< option  value = "3" >3</ option >
</ select >
< input  type = "button"  value = "修改"  onclick = "change()"  />
Copy after login

The js code to obtain the text of the selected item in the tag are as follows:

1) Dynamically create select

function  createSelect(){
var  mySelect = document.createElement( "select" );
mySelect.id =  "mySelect" ;
document.body.appendChild(mySelect);
}
Copy after login

2) Add option option

function  addOption(){
//根据id查找对象,
var  obj=document.getElementById( &#39;mySelect&#39; );
//添加一个选项
obj.add( new  Option( "文本" , "值" ));
}
Copy after login

3) Delete all options option

function  removeAll(){
var  obj=document.getElementById( &#39;mySelect&#39; );
obj.options.length=0;
}
Copy after login

4) Delete one option option

function  removeOne(){
var  obj=document.getElementById( &#39;mySelect&#39; );
//index,要删除选项的序号,这里取当前选中选项的序号
var  index=obj.selectedIndex;
obj.options.remove(index);
}
Copy after login

5) Get the value of option option

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index].value;
Copy after login

6) Get the text of option option

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index].text;
Copy after login

7) Modify option option

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index]= new  Option( "新文本" , "新值" );
Copy after login

8) Delete select

function  removeSelect(){
var  mySelect = document.getElementById( "mySelect" );
mySelect.parentNode.removeChild(mySelect);
}
Copy after login

The above is the detailed content of Detailed explanation of how to set the default selected options for the