javascript operations select element instance analysis

  • 2020-05-19 04:14:44
  • OfStack

This example demonstrates the use of the javascript operation select element. Share with you for your reference. The specific analysis is as follows:

Here you are familiar with the operation of js on select element. html page creates an form, which contains an select element and an submit button.

When you select an item in select, change its text, and when all items in select have their text changed, restore them.

Close the window itself when you press submit. The code is as follows:


<!DOCTYPE html>
<html>
<head>
<title>duang for select elements</title>
<script type="text/javascript">
 function do_change(elt){
  var text = elt[elt.selectedIndex].innerHTML;
  if(!text.match(/\[/))
   elt[elt.selectedIndex].innerHTML += " [duang]";
  var is_all_seleted = true;
  for(var i=0;i<elt.length;++i){
   if(!elt[i].innerHTML.match(/\[/)){
    is_all_seleted = false;
    break;
   }
  }
  if(is_all_seleted){
   alert("all duang!!!\nand reset it!!!");
   for(var i=0;i<elt.length;++i){
    elt[i].innerHTML = elt[i].innerHTML.replace(/\s\[.*\]/,"")
   }
  }
 }
</script>
</head>
<body>
 <form id="frm_main" action="#" method="post">
  <select id="slt" onchange="do_change(this);">
   <option value="opt_1">opt A</option>
   <option value="opt_2">opt B</option>
   <option value="opt_3">opt C</option>
   <option value="opt_4">opt D</option>
   <option value="opt_5">opt E</option>
  </select>
  <input type="submit" value="close window" onclick="window.close();"/>
 </form>
</body>
</html>

In firefox, 1 seemed unable to close the window itself at first, but it was later found that dom.allow_scripts_to_close_windows was set to true in about:config.

If the options in each select do not change regularly, you can write 1 on_change_ex to handle it. The code is as follows:


function do_change_ex(me){
  var text = me[me.selectedIndex].innerHTML;
  if(!text.match(/\[/)){
   me[me.selectedIndex].text_bak = me[me.selectedIndex].innerHTML;
   me[me.selectedIndex].innerHTML += " [duang]";
   me[me.selectedIndex].is_changed = true;
  }
  var is_all_seleted = true;
  for(var i=0;i<me.length;++i){
   if(!me[i].is_changed){
    is_all_seleted = false;
    break;
   }
  }
  if(is_all_seleted){
   alert("all duang!!!\nand reset it!!!");
   for(var i=0;i<me.length;++i){
    me[i].innerHTML = me[i].text_bak;
    me[i].is_changed = false;
   }
  }
}

I hope this article has been helpful to your javascript programming.


Related articles: