jQuery: Add options to a drop-down list using jQuery
jQuery Practical exercise Part - I : Exercise-31
Add options to a drop-down list using jQuery.
Sample Solution:
HTML Code :
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Add options to a drop-down list using jQuery.</title>
</head>
<body>
<p>List of Colors :</p>
<select id='myColors'>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="White">White</option>
<option value="Black">Black</option>
</select>
</body>
</html>
JavaScript Code:
var myOptions = {
val1 : 'Blue',
val2 : 'Orange'
};
var mySelect = $('#myColors');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
See the Pen jquery-practical-exercise-31 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Change button text using jQuery.
Next: Set background-image using jQuery CSS property.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/jquery-exercises/part1/jquery-practical-exercise-31.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics