Add and delete options dynamically in JS

Source: Internet
Author: User
1. dynamically create selectfunctioncreateSelect () {varmySelectdocument. createElement (& quot; select & quot;); mySelect. id & quot; mySelect & quot; document. body. appendChild (mySelect);} 2. 1. dynamically create select function createSelect () {var mySelect = document. createElement ("select"); mySelect. id = "mySelect"; document. body. appendChild (mySelect);} 2. add option function addOption () {// search for objects by id, var obj = document. getElementById ('myselect'); // Add an option obj. add (new Option ("text", "value"); // This is only valid in IE. options. add (new Option ("text", "value"); // compatible with IE and firefox} 3. delete all options option function removeAll () {var obj = document. getElementById ('myselect'); obj. options. length = 0;} 4. delete an optional optionfunction removeOne () {var obj = document. getElementById ('myselect'); // index. The sequence number of the option to be deleted. The number var index = obj of the selected option is used here. selectedIndex; obj. options. remove (index);} 5. obtain the option value var obj = document. getElementById ('myselect'); var index = obj. selectedIndex; // The serial number. The serial number var val = obj. options [index]. value; 6. obtain the option text var obj = document. getElementById ('myselect'); var index = obj. selectedIndex; // The serial number. The serial number var val = obj. options [index]. text; 7. modify optionvar obj = document. getElementById ('myselect'); var index = obj. selectedIndex; // The serial number. The serial number var val = obj. options [index] = new Option ("new text", "new Value"); 8. delete select function removeSelect () {var mySelect = document. getElementById ("mySelect"); mySelect. parentNode. removeChild (mySelect);} the complete code for the entire instance is as follows:
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.