Option content");" statement to append new options; 2. Use "$("select").prepend(" ");" Add options at the beginning."/> Option content");" statement to append new options; 2. Use "$("select").prepend(" ");" Add options at the beginning.">
Home >Web Front-end >Front-end Q&A >How to add options to select in jquery
Two methods: 1. Use the "$("select").append("");" statement to append new options; 2. Use "$( "select").prepend("");" Add options at the beginning.
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>
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)
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 ='新选项'>新选项</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>
2. prepend( ) method
prepend ( ) method inserts content "at the beginning" inside the selected element.
$(A).prepend(B)
means inserting B at the beginning of A.
Implementation example:
<script> $(document).ready(function() { $("button").click(function() { var $op = "<option value ='新选项'>新选项</option>"; $("select").prepend($op); }); }); </script>
[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!