Q:

How to Add Options to a Select Box from a JS Object using jQuery

0

How to Add Options to a Select Box from a JS Object using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery $.each() Function

You 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.5.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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Replace innerHTML of a Div using jQuery... >>
<< How to Get the ID of an Element using jQuery...