JS on the select control option option to add or delete the sample code

  • 2020-03-26 21:35:29
  • OfStack

Javascript operation select is a common form, the following are several common JS dynamic operation select methods:
 
//Create select dynamically
function createSelect() 
{ 
var mySelect = document.createElement("select"); 
mySelect.id = "mySelect"; 
document.body.appendChild(mySelect); 
} 

 
//Add options
function addOption() 
{ 
//Looking up objects by id,
var obj=document.getElementById('mySelect'); 
//Add an option
obj.add(new Option(" The text "," value ")); //This only works in IE
obj.options.add(new Option("text","value")); //This is compatible with IE and firefox
} 

 
//Delete all options
function removeAll() 
{ 
var obj=document.getElementById('mySelect'); 
obj.options.length=0; 
} 

 
//Remove an option
function removeOne() 
{ 
var obj=document.getElementById('mySelect'); 
//Index, to delete the sequence number of the option, take the sequence number of the currently selected option
var index=obj.selectedIndex; 
obj.options.remove(index); 
} 

 
//Gets the text of the option
var obj=document.getElementById('mySelect'); 
var index=obj.selectedIndex; //Serial number, take the serial number of the currently selected option
var val = obj.options[index].text; 

 
//Modify option
var obj=document.getElementById('mySelect'); 
var index=obj.selectedIndex; //Serial number, take the serial number of the currently selected option
var val = obj.options[index]=new Option(" New text "," The new value "); 

Related articles: