How to Use JSON Data to Populate the Options of a Select Box

Get data from JSON file to populate dropdown and display other data on select dropdown

If you get the json with a http request, you should pass it to the global variable

var url = "devices.json";
let data;
$.getJSON(url, function (_data) {
data = _data;
/* no other change */

$(document).ready(function(){
var url = "devices.json";

const data = [{
"options": "Option 1 on dropdown",
"result1": "Text to populate div1 - 1",
"result2": "Text to populate div2 - 1"
},
{
"options": "Option 2 on dropdown",
"result1": "Text to populate div1 - 2",
"result2": "Text to populate div2 - 2"
},
{
"options": "Option 3 on dropdown",
"result1": "Text to populate div1 - 3",
"result2": "Text to populate div2 - 3"
}]
//$.getJSON(url, function (data) {
$.each(data, function (index, value) {
$('#sel').append('<option value="' + index + '">' + value.options +
'</option>');


});
// });

$("select").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");

if(optionValue){
$("#sol").text(data[optionValue].options);
$("#div1").text(data[optionValue].result1);
$("#div2").text(data[optionValue].result2);
$(".box").show();
/*
$(".box").not("." + optionValue).hide();
$("#sol").text(optionValue);
$("." + optionValue).show();
*/
} else{
$(".box").hide();
}
});
}).change();
});
.box{
color: #fff;
padding: 20px;
display: none;
margin-top: 20px;
}

body {
background: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel">
<option value="">Select option</option>
</select>
<div class="box" id="sol"></div>
<div class="box" id="div1"></div>
<div class="box" id="div2"></div>

jQuery-- Populate select from json

I would do something like this:

$.each(temp, function(key, value) {
$select.append(`<option value="${key}">${value}</option>`);
});

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

populate select option with JSON data

Solution

Worked when Array was converted to Object

$.get("JSON.php?value=two", function(response) 
{
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}

if (response != '')
{
var response2 = JSON.parse(response);
$('#dropdown').find('option').remove();
$.each(response2,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value +
'</option>');
});
}
)};

populate select options from json data and create a form request

You can use $("form").on("submit".. event this will get called when submit button is clicked then use .serialize() to get all inputs values as key-value pairs and then pass same inside your ajax call.

Demo code :

$(document).ready(function() {
//this is for demo...
var data = {
"data": [{
"name": "ABC-1",
"id": 32
}, {
"name": "ABC-2",
"id": 33
}]
}
//uncomment below to use ..
/* $.ajax({
type: "GET", //change this if needed to post
url: "https://jsonkeeper.com/b/76PF",
success: function(data) {*/
console.log("result will come here")
var ids = "",
names = "";
//loop through datas
$(data.data).each(function(i, val) {
//append option
names += "<option>" + val.name + "</option>";
ids += "<option>" + val.id + "</option>";
})
$("select[name=name]").html(names)
$("select[name=id]").html(ids)
/*}
})*/

$("form").on("submit", function(e) {
e.preventDefault()
console.log($(this).serialize())
$.ajax({
type: "GET", //change this if needed to post
url: "https://localhost/somename?" + $(this).serialize(), //your link
success: function(data) {
console.log("result will come here")

}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h3>Select name</h3>
<select name="name">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>

<h3>Select ID</h3>
<select name="id">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<br>
<br>
<input type="submit">
</form>

How to use PHP to populate a select Dropdown with json data

you can use ' and " together:

  <select id="printer" name="printer">
<option value="none">Select Printer</option>
<?php
foreach($test as $t) {
echo '<option value="'. $t['Name']. '">'. $t['Name'].'</option>';
}
?>
</select>

How to populate dropdown items from JSON?

You can loop through the JSON and append() the values:

var json = {  "serverTypes": ["WINDOWS", "LINUX"]};for (var x = 0; x < json.serverTypes.length; x++ ) {  var option = json.serverTypes[x];  $('#serverTypes').append('<option value="' + option + '">' + option + '</option>')}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select id="serverTypes" name="serverType" class="form-control"></select>

Json data populate in select option where data in side another array

  • Don't append inside loops. Append only once outside of a loop
  • Use Array.prototype.reduce() to reduce an array into a Document Fragment
  • Use new DocumentFragment() and append your Options inside it
  • Append your fragment to a destination Element
  • It's useful to create a reusable function that does what it says like i.e: populateExchange() that accepts the data Object response as argument
  • $.ajax default "type" is "GET" - so no need to re-override the default.

const populateExchange = (res) => {
const options = res.data.reduce((DF, item, i) => {
const opt = new Option(item.exchangeName, item.exchangeCode, false, !i);
if (!i) opt.disabled = true;
DF.append(opt);
return DF
}, new DocumentFragment());
$("#ExchCode").append(options); // Append outside the loop
};

// DEMO ONLY:
populateExchange({
"status": "200",
"success": true,
"mesg": "data found",
"data": [
{"exchangeCode": "0","exchangeName": "-SELECT EXCHANGE HOUSE-"},
{"exchangeCode": "24NME","exchangeName": "PAYPAL"},
{"exchangeCode": "AAM112","exchangeName": "AL AHALIA "},
{"exchangeCode": "ZEN042","exchangeName": "ZENJ EXCHANGE CO. W.L.L,"},
]
});

// USE LIKE:
jQuery($ => { // DOM Ready and $ alias in scope
$.ajax({
url: 'fetch-data.php',
success: populateExchange
});
});
<select id="ExchCode" class="form-control" name="ExchCode" autocomplete="off" required></select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


Related Topics



Leave a reply



Submit