Home >Web Front-end >JS Tutorial >Example analysis of javascript operation select element_javascript skills
The example in this article describes the use of javascript to operate the select element. Share it with everyone for your reference. The specific analysis is as follows:
Here, let’s get familiar with the operation of js on the select element. Create a form in the html page, which contains a select element and submit button.
Change the text when an item in the select is selected, and restore them after the text of all items in the select is changed.
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, it seemed that the window itself could not be closed at first. Later, I found that setting dom.allow_scripts_to_close_windows in about:config can be set to true.
If the options in each select change irregularly, you can write an 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 will be helpful to everyone’s JavaScript programming design.