Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to add and delete elements to the select drop-down box using JavaScript

黄舟
Release: 2017-03-22 14:46:14
Original
2858 people have browsed it

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=&#39;0&#39;>---请选择---</option>
     <option value=&#39;1&#39;>男</option><option value=&#39;2&#39;>女</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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!