How to select values from a JSON object using jQuery ?
In this article, we will select values from a JSON object and display them on the browser using jQuery. To select values from a JSON object to webpage, we use append() method.
This append() method in jQuery is used to insert some content at the end of the selected elements.
Syntax:
$(selector).append( content, function(index, html) )
Approach: First we store a JSON object containing (key, value) pair in a variable. We have created a button using <button> element and when we click the button, the jQuery function called with selector and click events. After click the button, the attr() method added the name attribute with <select> element. The <option> element is appended to each element using append() and each() methods.
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > How to select values from a JSON object using jQuery? </ title > <!-- Import jQuery cdn library --> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > < script > $(document).ready(function () { var json = [ { "name": "GFG", "text": "GFG" }, { "name": "Beginner", "text": "Beginner" }, { "name": "w3wiki", "text": "w3wiki" } ]; $('button').click(function () { var select = $("< select ></ select >") .attr("name", "cities"); $.each(json, function (index, json) { select.append($("< option ></ option >") .attr("value", json.name).text(json.text)); }); $("#GFG").html(select); }); }); </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > w3wiki </ h1 > < h3 > How to select values from a JSON object using jQuery? </ h3 > < div id = "GFG" ></ div > < button >Submit</ button > </ body > </ html > |
Output:
Before Click Button:
After Click Button:
Contact Us