$.each()
FunctionYou can use the jQuery $.each()
function to easily populate a select box (dropdown list) using the values from a JavaScript object. The $.each()
function can be used to iterate over any collection, whether it is an object or an array. Let's try out an example to see how it actually works:
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Add Options to a Select from a JS Object</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
// Sample JS object
var colors = { "1": "Red", "2": "Green", "3": "Blue" };
$(document).ready(function(){
var selectElem = $("#mySelect");
// Iterate over object and add options to select
$.each(colors, function(index, value){
$("<option/>", {
value: index,
text: value
}).appendTo(selectElem);
});
});
</script>
</head>
<body>
<label>Color:</label>
<select id="mySelect">
<option value="0">Select</option>
</select>
</body>
</html>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to get all the keys of an associative array in PHP
Use the PHP array_keys() funct...How to count all elements or values in an array in PHP
Use the PHP count() or si...How to Check Whether a String Contains a Substring in JavaScript
Use the indexOf() Method Th...How to check or uncheck radio button dynamically using jQuery
Use the jQuery prop() method You can...How to Replace innerHTML of a Div using jQuery
Use the jQuery html() Method You can...