Home >Web Front-end >JS Tutorial >Detailed explanation of how to add and delete elements to the select drop-down box using JavaScript
This article mainly introduces the JavaScript method to add and delete elements to the select drop-down box, involving related skills of append() and remove() methods in jQuery to dynamically operate form elements, which are required Friends can refer to the following
The example of this article describes the method of adding and deleting elements to the select drop-down box using JavaScript. Share it with everyone for your reference, the details are as follows:
1. Instructions
a. Use the append()
method to add elements to the drop-down box
b. Use the remove()
method to remove the last element in the drop-down box
2. Example source code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript向select下拉框中添加和删除元素</title> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> /** * 向select下拉框中添加子元素 */ function addElement() { //保证不重复添加 $("#select_p").empty(); //添加子元素 $("#select_p").append("<option value='0'>---请选择---</option> <option value='1'>男</option><option value='2'>女</option>"); } /** * 删除下拉框中最后一个元素 */ function removeLast() { //删除最后一个子元素 $("#select_p option:last").remove(); } </script> </head> <body> </body> <p id="select_span"> <select id="select_p" style="width:145px;"> </select> </p> <input type="button" value="添加元素" onclick="addElement()"/> <input type="button" value="删除元素" onclick="removeLast()"/> </html>
3. Implementation results
(1) During initialization
(2) Add elements
(3) Delete element
The above is the detailed content of Detailed explanation of how to add and delete elements to the select drop-down box using JavaScript. For more information, please follow other related articles on the PHP Chinese website!