Set value on select options to select JSON data - javascript

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.

Related

Convert JSON data to a select dropdown in React

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>

Auto pre-select dropdown value from URL address

I'm using the dropdown select menu which redirects users to selected cities. I have searched for this topic everywhere and tried many solutions found on stackoverflow but each of them did not work. In many cases it even disabled the redirection of my dropdown. So I am posting a new question. Hopefully that someone could solve my problem.
Problem: When I visit URL I see select delivery city - non value option. It should show the selected city based on URL address.
My URL looks like this /kategoria-produktu/CITY U SELECT (/kategoria-produktu/cadca/)
To sum up: When u visit url /kategoria-produktu/cadca the dropdown should be preselect on current url and display Čadca.
Any ideas how could I solve this?
Thank you very much!
CODE
JS
if(location.href.indexOf(localStorage.country) == -1){
location.href = localStorage.country
}
function formChanged(form) {
var val = form.options[form.selectedIndex].value;
if (val !== 'non-value') {
if (localStorage) {
localStorage.country = val;
}
if (!location.href.indexOf(val)) {
location = val;
}
}
}
HTML
<form name="form1">
<select id="saleTerm" onchange="formChanged(this); location =
this.options[this.selectedIndex].value;" NAME="country" SIZE="1">
<OPTION VALUE="non-value">Select delivery city</option>
<OPTION VALUE="/kategoria-produktu/cadca/">Čadca</option>
<OPTION VALUE="/kategoria-produktu/brno/">Brno</option>
<OPTION id="bratislava" VALUE="/kategoria-produktu/bratislava/">Bratislava</option>
</select>
</form>
So a bunch of little things need to change here for you to get what you want. I'll try to write them all down:
You should access localStorage using getItem and setItem like in the localStorage MDN documentation
Use an event listener instead of the inline onchange attribute, it's much cleaner.
You probably want to use includes instead of indexOf since you are looking for a substring (country) in a string (href), indexOf won't do this for you.
I used location.pathname since you really only care about the path, there are better ways to get the exact path parameter you want.
No need to use a <form/> as far as I can see from the code you shared.
I removed /kategoria-produktu/ from the option's value attribute since its repetitive and just placed it once in the js
You should change the value of the select to the city you want as the default selected. You can do this by parsing out the city from the path and setting it as the value attribute on the select
I think that's it, here is an example using those points above.
const PREFIX = "kategoria-produktu";
window.addEventListener('load', function() {
let countryInStorage = localStorage.getItem("country");
if (countryInStorage && !location.pathname.includes(countryInStorage)) {
location.href = `/${PREFIX}/${countryInStorage}`;
}
document.getElementById("saleTerm").addEventListener("change", formChanged);
setDefaultOption();
})
function setDefaultOption() {
let countryPath = location.pathname.split("/")[2];
if (countryPath) {
document.getElementById("saleTerm").value = countryPath;
}
}
function formChanged() {
let selectedCountry = this.value;
if (selectedCountry !== "non-value") {
if (localStorage) {
localStorage.setItem("country", selectedCountry);
}
if (!location.pathname.includes(selectedCountry)) {
location.href = `/${PREFIX}/${selectedCountry}`;
}
}
}
<select id="saleTerm" name="country">
<option value="non-value">Select delivery city</option>
<option value="cadca">Čadca</option>
<option value="brno">Brno</option>
<option value="bratislava">Bratislava</option>
</select>
If I understand it correctly, you are looking onto showing the proper option from the select element based on the URL.
Look at the example below. It basically runs a process on page load and when the DOM is ready (hence DOMContentLoaded) to check if an option based on URL exists in the select options and picks that. You may have to update your logic depending on the URL structure. The example below assumes your URL is always formatted like http://your.domain.com/kategoria-produktu/<city>/.
document.addEventListener("DOMContentLoaded", function() {
// find the option based on the URL.
let option = document.querySelector("#saleTerm > option[value='" + location.pathname + "']");
// assign the option value to the select element if such exists.
if (option) {
document.querySelector("#saleTerm").value = option.value;
}
});

display a part of value in select option

I have a select drop-down with country and code. In drop-down option, for user experience and understanding i am displaying name of the country along with country code.
As a normal functionality when a user selects any value from the drop-down that value gets displayed inside the input like this
however i want that only the country code should get displayed like this
Part of my code
<select name="countrycode" class="form-control pf-country" id="countrycode">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The entire code is available here
Can anyone please suggest how to do it.
As per my understanding, You can try this one. As this example providing exact output as you mentioned in your questions.
https://silviomoreto.github.io/bootstrap-select/examples/#selected-text
Basically we're trying to change innerText of selected-option. It can be achieved easily by adding onchange event listener to the select tag.
But there's a little problem, on changing innerText we lose previous value of innerText, solution by #KKK solves problem but leaves this little thing.
Following code handles problem in complete ways. We're adding data-innerText atribute with previous value of innerText and also id="previous" to identify it. Please check this demo.
function simpleTweak(select){
var previouslySelectedTag = document.getElementById('previous');
if(previouslySelectedTag!=undefined){
previouslySelectedTag.innerText = previouslySelectedTag.getAttribute('data-innerText');
previouslySelectedTag.setAttribute('id','');
}
var innerText = select.options[select.selectedIndex].innerText;
select.options[select.selectedIndex].setAttribute('data-innerText',innerText);
select.options[select.selectedIndex].setAttribute('id','previous');
var value="(+"+select.options[select.selectedIndex].value+")";
select.options[select.selectedIndex].innerText = value;
}
As I understood, you need to change the display text after selecting the option, is it? If so, you can do it like this.
You can set the selected index's text in onchange event. But it will reset the text in the option when you click the dropdown again. You may need to change it back if you prefer.
function displayCountryCode() {
var countrycode = document.getElementById("countrycode");
countrycode.options[countrycode.selectedIndex].text = '+' + countrycode.value;
}
<select name="countrycode" class="form-control pf-country" id="countrycode" onchange="displayCountryCode()">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The following JavaScript code will change the text of the selected option when you select it and change it back when you select a different one.
It does this by saving the values of the country name and country number as HTML5 data attributes (option.dataset.countryName & option.dataset.countryNumber)
Doing it this way, you don't have to change the format of the HTML from what you provided in your post.
I used vanilla JavaScript, so it'll work with or without jQuery.
window.addEventListener('load', () => {
let select = document.getElementsByName('countrycode')[0]
let options = document.getElementsByTagName('option')
for (let i = 1; i < options.length; i++) {
let option = options[i]
let matches = option.innerText.match(/(.*?) (\(\+\d+\))/)
option.dataset.countryName = matches[1]
option.dataset.countryNumber = matches[2]
// Set the value in the collection again now that the object has been changed
options[i] = option
}
select.addEventListener('change', () => {
for (let i = 1; i < options.length; i++) {
let option = options[i];
option.innerText = option.dataset.countryName + ' '
option.innerText += option.dataset.countryNumber
}
let option = document.querySelector('option:checked')
if (option !== options[0]) {
option.innerText = option.dataset.countryNumber
}
})
})
There's also a demo at CodePen

Value from comma separated select option values and append the second value to a other select option

i'm struggling with a question, how i can get the value from comma separated select option value and append the second value to a other select option?
My html looks
<select id="firstSelecter_ID1">
<option value"first value, second value, third value">option1</option>
<option value"first value, second value, third value">option2</option>
<option value"first value, second value, third value">option3</option>
<option value"first value, second value, third value">option4</option>
</select>
<select id="secondSelecter_ID2">
<option value"second value">option1-a</option>
<option value"second value">option2-a</option>
<option value"second value">option3-a</option>
<option value"second value">option4-a</option>
</select>
var entry6 = $('#Id_6')
entry6.on('change', 'select#firstSelecter_ID1', function (e) {
...
option value ,second .append() to #secondSelecter_ID2 as new option value =""
...
}
Many thanks if somebody can give me the idea and I hope I have asked the question right and understandable
Regards Maty
Try something like
$('#select_1 option').each(function(){
var secondVal = this.value.split(',')[1].trim(),
$opt = $('<option>').val(secondVal).text($(this).text());
$('#select_2').append($opt);
});
Ok, i got it to work how i need it...
entry1.on('change', 'select#actiontypeSelect', function (e) {
$("select#secondSelecter_ID2 option:eq(1)").remove();
$("select#secondSelecter_ID2 option:last").remove();
$('select#actiontypeSelect').each(function () {
var value1 = $('select#actiontypeSelect').find("option:selected").val();
var secondVal = value1.split(',')[1].trim(),
$opt = $('<option>').val(secondVal).text('Exclusive Equipment');
$('#secondSelecter_ID2').append($opt);
console.log(value1);
});
$("select#secondSelecter_ID2").append('<option value="0.00">Inclusive Equipment</option>');
e.preventDefault();
});
This gives me from the selected option the second value and append as a new option with the value to other select box.
Special thanks to #charlietfl he gives me the right way.

<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);

Categories

Resources