Use js to implement an editable select drop down list

  • 2020-03-30 02:05:11
  • OfStack

 
<select id="name" name="name" 
onkeydown="clearSelect(this,event);" 
onkeypress="writeSelect(this,event);" style="width:70px;"> 
<option value=""></option> 
<option value="test1">test1</option> 
<option value="test2">test2</option> 
<option value="test3">test3</option> 
</select> 

<script> 
function clearSelect(obj,e) 
{ 
opt = obj.options[0]; 
opt.selected = "selected"; 
if((e.keyCode== 8) ||(e.charCode==8))//Use the backspace key to edit verbatim deletion
{ 
opt.value = opt.value.substring(0, opt.value.length>0?opt.value.length-1:0); 
opt.text = opt.value; 
} 
if((e.keyCode== 46) ||(e.charCode==46))//Use the Delete key to edit verbatim Delete
{ 
opt.value = ""; 
opt.text = opt.value; 
} 
//Other key responses can also be implemented
} 

function writeSelect(obj,e) 
{ 
opt = obj.options[0]; 
opt.selected = "selected"; 
opt.value += String.fromCharCode(e.charCode||e.keyCode); 
opt.text = opt.value; 
} 
function forbidBackSpace()//In order to avoid backspace's return to the previous page in IE and the edit function of this drop-down box, we need to disable backspace's function. ForbidBackSpace can be written in <Body onkeydown = "forbidBackSpace ();"> In the.
{ 
if((event.keyCode == 8) && (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password")) 
{ 
event.keyCode = 0; 
event.returnValue = false; 
} 
} 
</script> 

Related articles: