jQuery each() add <option> to <select>

Introduction

You can use the jQuery each() function to populate a select box.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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,//  w w  w .j  a v  a  2s  .c  o  m
            text: value
        }).appendTo(selectElem);
    });
});
</script>
</head>
<body>
    <label>Color:</label>
    <select id="mySelect">
        <option value="0">Select</option>
    </select>
</body>
</html>



PreviousNext

Related