How to add options to select in jquery

青灯夜游
Release: 2022-05-30 12:01:32
Original
5492 people have browsed it

Two methods: 1. Use the "$("select").append("");" statement to append new options; 2. Use "$( "select").prepend("");" Add options at the beginning.

How to add options to select in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer. The

select element creates a single-select or multiple-select menu. The option tag in the select element is used to define the options available in the list.

<select>
  <option value ="volvo">Volvo</option>
  <option value ="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
Copy after login

How to add options to select in jquery

Therefore, adding options to select is to add option sub-element tags to the select tag.

jquery can use the following two methods to add options (option sub-elements) to select:

  • append() method

  • prepend() method

1. append() method

append() method goes inside the selected element Insert content "at the end".

$(A).append(B)
Copy after login
  • means inserting B at the end of A.

Implementation example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").click(function() {
					var $op = "<option value =&#39;新选项&#39;>新选项</option>";
					$("select").append($op);
				});
			});
		</script>
	</head>

	<body class="ancestors">
		<select>
		  <option value ="volvo">Volvo</option>
		  <option value ="saab">Saab</option>
		  <option value="opel">Opel</option>
		  <option value="audi">Audi</option>
		</select><br><br>
		<button>给select增加选项</button>
	</body>

</html>
Copy after login

How to add options to select in jquery

2. prepend( ) method

prepend ( ) method inserts content "at the beginning" inside the selected element.

$(A).prepend(B)
Copy after login
  • means inserting B at the beginning of A.

Implementation example:

<script>
	$(document).ready(function() {
		$("button").click(function() {
			var $op = "<option value =&#39;新选项&#39;>新选项</option>";
			$("select").prepend($op);
		});
	});
</script>
Copy after login

How to add options to select in jquery

[Recommended learning: jQuery video tutorial, web front-end Development

The above is the detailed content of How to add options to select in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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