Convert JSON data to a select dropdown in React - javascript

I have seen a similar question here (how to display json data in dropdown using reactj), but it does not answer my query.
I have some JSON data coming in from an ajax request in my react app:
"quotes":{
"USDAED":3.6732,
"USDAFN":77.588904,
"USDALL":103.298421,
"USDAMD":528.084946,
"USDANG":1.795181,
"USDAOA":628.150147,
"USDARS":92.5812
}
Its a list of currencies and their conversion rates.
I need to render a select dropdown list out of it in a react component such that the json data is transformed into keys and values:
<select className="dropdown">
<option key="USDAED" value="3.6732">USDAED</option>
<option key="USDAFN" value="77.588904">USDAFN</option>
...
Is there an easy way to traverse the json data and create a select dropdown in JSX?

I see only one difference between your situation and the SO example: in the example the list of items is an array, in your situation it's the fields of an object.
using Object.keys() you can get an array of fields, and use a map on this array to display all the options
<select>
{Object.keys(quotes).map(element => <option key={element} value={quotes[element]}>{element}</option>)}
</select>
https://codepen.io/sanjar/pen/YzNLRWE?editors=0011

you can iterate through your object keys
Updated my answer to show html
var data = {
"quotes": {
"USDAED": 3.6732,
"USDAFN": 77.588904,
"USDALL": 103.298421,
"USDAMD": 528.084946,
"USDANG": 1.795181,
"USDAOA": 628.150147,
"USDARS": 92.5812
}
};
var result=[];
for (let key in data.quotes) {
var ele = document.getElementById('sel');
result.push({key:key,value:data.quotes[key]})
ele.innerHTML += '<option value="' + key + '">' + data.quotes[key] + '</option>';
}
console.log(result)
<select className="dropdown" id="sel">
<option value="">-- Select --</option>
</select>

Related

How do I pass multiple values through <option> value?

I'm making a online shopping item page,
it gets the 'item_id' to loop through a item info db to show its info on the page(price,image,name,whatev)
while using that same 'item_id' to loop through an inventory table(the inventory table has color_id, size_id ,item_id and storage_id) to render a drop down menu(select) to show its color options of that specific item,
i'm using ajax to get the size options of that color_id from the same inventory table. but i can't get the both 'item_id' and color_id passed through the color to narrow down the query together with color_id .
is there a way that i can pass both color_id and item_id through the rendered color to query in inventory table to get the storage_id? because right now i can't narrow it down the the specific item, it gets the size option of a specific color(color_id) but of all items, if without item_id
basically i'm trying to filtering down to the specific storage_id using two drop down menu(color_id ,size_id and product_id) of same table. but having trouble passing 2 (or multiple) values at once.
hope this makes sense?
<select class="form-control" id="colorSelector" onchange = "getSize(this.value)">
<option value="">Select Color</option>
<?php show_color_option()?> --->this is another function to render the colors using item_id
</select>
function getSize(val){
$.ajax({
type:'POST',
url:'sizeoptions.php',
data:"color_id="+ val,
success:function(data){
$('#sizeSelect').html(data);
}
});
}
function getSku(val){
}
///////////////////////////////////sizeoptions.php//////////////////
<?php
if(isset($_POST['color_id'])){
$query = query("SELECT size_id FROM inventory WHERE color_id =
".escape_string($_POST['color_id'])." GROUP BY size_id ");
confirm($query);
while($row = fetch_array($query)){
$p_size = display_size($row['size_id']);
$size_options = <<<DELIMETER
<option value="{$row['size_id']}"> {$p_size} </option>
DELIMETER;
echo $size_options;
}
}
?>
You can get extra information from select box using attributes.
<select class="form-control" id="colorSelector" onchange = "getSize()">
<option value="xyz" extra-attr="abc">Select Color</option>
</select>
function getSize(){
var selectedXYZ = $("#colorSelector").val();
var selectedABC = $("#colorSelector").find("option:selected").attr('extra-attr');
}

Set value on select options to select JSON data

I'm creating a select based on the JSON I got with an API. Based on that select, when I choose another option I want some data to change (text and image src).
I got the select with the options done. Each option is a name and I done that with forEach. My problem is setting the value so I can use it to change the other data. In my mind the easiest solution would be setting the value to the objects index so when I choose the first option I get 0 and can get the first JSON object. I'm not sure if this is the best way anyway.
This is my code reduced to only the forEach:
<select name="select" id="selector"> </select>
data_json.show.forEach((element) => {
document.getElementById('selector').innerHTML +=
`<option value="">${element.name}</option>`;
});
(the value is what I want to be the same as the index of each json data)
My idea of what I want to get:
<select name="select" id="selector">
<option value="0">Name_01</option>
<option value="1">Name_02</option>
<option value="2">Name_03</option>
</select>
So I can use the value like this:
let titulos = document.getElementById("titulos");
selectVal.onchange = function() {
let actualVal = selectVal.options[selectVal.selectedIndex].value;
titulos.innerHTML = "Títulos:" + " " + data_json.show[actualVal].image;;
};
<p id="titulos">Títulos:</p>
Hope it makes sense
You're setting them all to an empty value. You can use the array index to give them each a different value.
data_json.show.forEach((element, index) => {
document.getElementById('selector').innerHTML +=
`<option value="${index+1}">${element.name}</option>`;
});
BTW, you can simplify selectVal.options[selectVal.selectedIndex].value to just selectVal.value.

<select> tag and returning multiple values to javascript method

I have an issue with the data which is sent from a drop down menu, the selector only returns a single value, even when multiple values are selected. I have searched online for a solution to this, but they all use PHP, JQuery or some method outside the scope of the course I am taking; to capture multiple selected items. I have tried .value of the individual options, but that returns all of the options rather than just the ones which are selected. Is there some kind of trick to sending multiple values?
Here is my code for the menu. For example If I select JAVA PROGRAMMING, NETWORKS and VIDEO GAMES, only JAVA PROGRAMMING is sent.
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
I have also tried using the Select Object in the DOM, http://www.w3schools.com/jsref/dom_obj_select.asp
which has a few methods for accessing the options in the dropdown menu. One method in particular called selectedIndex, seemed to be what I am looking for, however it only returns the the index of the first selected option, instead of all of the selected options.
Is there a simple solution to this using just Javascript and the DOM?
Thanks
- Chris
Get the options, iterate and check if they are selected, and add the values to an array
var select = document.getElementById('CK_Expertise'),
options = select.getElementsByTagName('option'),
values = [];
for (var i=options.length; i--;) {
if (options[i].selected) values.push(options[i].value)
}
console.log(values)
FIDDLE
or being a little more fancy
var select = document.getElementById('CK_Expertise'),
values = Array.prototype.filter.call(select.options, function(el) {
return el.selected;
}).map(function(el) {
return el.value;
});
console.log(values)
FIDDLE
You could use the select.selectedOptions property:
select.onchange = function() {
var values = [].map.call(this.selectedOptions, function(opt){
return opt.value;
});
};
document.getElementById('CK_Expertise').onchange = function() {
document.querySelector('pre').textContent = JSON.stringify([].map.call(
this.selectedOptions, function(opt){ return opt.value; }
));
}
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
<pre></pre>
If you can use jQuery, this will give you all the values
$(document).ready(function(){
$('#CK_Expertise').change(function(e){
var values = $('#CK_Expertise').val()
alert(values);
});
});
HTH,
-Ted
You could iterate storing select.selectedIndex in an array and unselecting the corresponding option to get the next one:
select.onchange = function() {
var i, indices=[], values = [];
while((i=this.selectedIndex) > -1) {
indices.push(i);
values.push(this.value);
this.options[i].selected = false;
}
while((i=indices.pop()) > -1)
this.options[i].selected = true;
console.log(values);
}
Demo
This way you avoid iterating over all options, but you must iterate twice over the selected ones (first to unselect them, them to select them again).
Why not using an indexed variable in the SELECT command?
<SELECT MULTIPLE id="stuff" name="stuff[]">
<OPTION value=1>First stuff</option>
<OPTION value=2>Second stuff</option>
<OPTION value=3>Third stuff</option>
</SELECT>
In that case it's easy to read the array:
$out=$_REQUEST['stuff'];
foreach($out AS $thing) {
echo '<br />'.$thing;
}
Sorry for the poor indentation, but I just wanted to show the way I use for solving this case!
var select = document.getElementById('CK_Expertise'),
options = select.selectedOptions,
values = [];
for(let i=0;i<options.length;i++)
{
values.push(options[i].value);
}
console.log(values);

Fill multiple select boxes with JSON data

I have got the following database table (there is more data in the database though, this is not all!):
catid value description
0 350 350 euro
0 500 500 euro
0 650 650 euro
1 0 No
1 1 Yes
With the help of PHP and json_encode() i'm creating a JSON string of this table:
jQuery171024539993586950004_1349776890005([{"0":"0","catid":"0","1":"350","value":"350","2":"350 euro","description":"350 euro"},{"0":"0","catid":"0","1":"500","value":"500","2":"500 euro","description":"500 euro"},{"0":"0","catid":"0","1":"650","value":"650","2":"650 euro","description":"650 euro"},{"0":"1","catid":"1","1":"0","value":"0","2":"No","description":"No"},{"0":"1","catid":"1","1":"1","value":"1","2":"Yes","description":"Yes"}])
Now what i want is to use the JSON to fill select boxes, just like you would in HTML:
<select id="0">
<option value="350">350 euro</option>
<option value="500">500 euro</option>
<option value="650">650 euro</option>
</select>
<select id="1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
Can anyone help me with this? I know how to do a loop to fill a table (with $.getJSON), but i'm kinda stuck with this one.
This function will loop through your posted object and populate the menus (given your posted source):
var populateSelects = function(data) {
var cat0 = $('select#0'),
cat1 = $('select#1'),
opt = $('<option />'),
newOpt = {},
cat0opts = [],
cat1opts = [];
$.each(data, function(i, obj) {
//clone the option element so as to not re-create a new one
newOpt = opt.clone();
//obj is the JavaScript object in the array, so
//dot-notation works nicely
newOpt.text(obj.description).val(obj.value);
if (obj.catid === "0") {
//push the DOM element, not the jQuery object
cat0opts.push(newOpt[0]);
} else if (obj.catid === "1") {
cat1opts.push(newOpt[0]);
}
});
//Add the array of DOM elements to their respective menus,
//clearing out any existing menu items.
cat0.empty().append(cat0opts);
cat1.empty().append(cat1opts);
};
Here's a fiddle of it in action: http://jsfiddle.net/a5MTE/1/
One note of importance is the catid comparison... if the parsed JSON returns catid as number (not a string) you'll want to change the comparison to if (obj.catid === 0).
by the json parsing you should have to make a parser and by if and else condition on addcat you will be able to do it

Populating select option dynamically with jquery

There will be two drop down lists,
First have the list of mobile vendor, and the second have the list of models per vendor.
When one select a vendor from the first drop down list, the second drop down list should populate with relevant model for that vendor dynamically. This is for mobile web site, it's better to use jquery-mobile
The option values for the second will in a json map.
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
selectValues = {"nokia" : {"N97":"download-link",
"N93":"download-link"},
"motorola": {"M1":"download-link",
"M2":"download-link"}}
<select class="model">
<option></option>
</select>
For example, if the user selects nokia in the first drop down list, the second drop down list should have N97, N93 as the options.
EDIT: New javascript to take into account your updated json structure:
$(function() {
var selectValues = {
"nokia": {
"N97": "http://www.google.com",
"N93": "http://www.stackoverflow.com"
},
"motorola": {
"M1": "http://www.ebay.com",
"M2": "http://www.twitter.com"
}
};
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
Working example is available in jsFiddle.
Note that this should work with jQuery mobile just fine.

Categories

Resources