In this tutorial we are going to see how to add a new <option> tag to an existing <select> drop down using jQuery.
Also we are going to learn how to add <option> to the top of the <select> drop down as well as bottom of the <select> drop down.
Here is a snippet: (To add an option tag to the top of the select)
$('#yourelementid').prepend('<option value="Apple">Apple</option>');
Here is a snippet: (To add an option tag to the bottom of the select)
$('#yourelementid').append('<option value="Frog">Frog</option>');
So, basically append() will add the tag to the bottom of the list and prepend() will add the tag to the top of the list.
Here is an another working example for you to play around with it:
<html> <head> <title>Add option to a Select (Drop down) using jQuery</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function(){ $('#mydropdown').prepend('<option selected value="Apple">Apple</option>'); $('#mydropdown').append('<option value="Frong">Frog</option>'); }); </script> </head> <body> <select id="mydropdown"> <option value="Ball">Ball</option> <option value="Cat">Cat</option> <option value="Dog">Dog</option> <option value="Egg">Egg</option> </select> </body> </html>
To ease, here is the demo: