Drop down menu with array, define value of each option - javascript

Hello there Stackoverflow!
Today I tried making a drop-down menu with an array. It did work, but the problem that has taken place after this, is to define the values printed by the array.
As of now, this is the code regarding the drop-down menu.
HTML
<select id="selectDestinasjon">
<option>Velg ett sted</option>
</select>
Javascript
var select = document.getElementById("selectDestinasjon");
var options = ["Konsberg", "Trysil", "Beitostølen"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
But I want to give each option a value, that I can later impliment into a calculator, because I want to make a booking service where each of these options has different value and the calculator retrieve info from current selected option, setting a price depending on selected option.
If anything seem unclear or too little detailed, please ask and I'll do my best to explain.
JSFIDDLE
https://jsfiddle.net/a3pe6zcu/

Are you looking for something like this? I have updated your data to hold the price and the name of the place. Now the select has the text as the place and the price as the value. Updated fiddle
var select = document.getElementById("selectDestinasjon");
var options = [{"place": "Konsberg","price":"$20"}, {"place":"Trysil","price":"$30"}, {"place":"Beitostølen","price":"$40"}];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt.place;
el.value = opt.price;
select.appendChild(el);
}

Related

php - How to keep select values after search click

I have a select tag that helps the user filter search results by years. I wish to keep the value of the selected option after clicking on 'search'.
I use php but for the select options I used JS:
var minA = new Date().getFullYear(),
maxA = 1900,
selectA = document.getElementById('selesctDatesOne');
for (var i = maxA; i<=minA; i++){
var optA = document.createElement('option');
optA.value = i;
optA.innerHTML = i;
selectA.appendChild(optA);
}
This is the html:
<select name="yearsFrom" id="selesctDatesOne" ></select>
I saw this thread but I can't figure out how to use it since I set the options via JS.
any idea how to approach this?

Prevent DOM elements from being added on every click

I have the following script which gets DOM elements with a given class, and adds them to an array. It then loops over the array and adds the values to option elements for a SelectControl component in WordPress Gutenberg. I'm able to get the elements into the array into the dropdown, but I'm receiving the following error: Uncaught TypeError: Cannot read property 'appendChild' of null in the console. It also doesn't show the selected option in the select component when selected and duplicates the array options in the dropdown every time an option from the dropdown is selected.
I suspect it may be an execution sequence issue, but not completely sure:
setTimeout(() => {
let headers = [...document.querySelectorAll('.wp-block-heading')].map(item => item.innerText);
const select = document.getElementById('selectheader');
for (let i = 0; i < headers.length; i++) {
let opt = headers[i];
let el = document.createElement('option');
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}, 1000);
<SelectControl
value={[headers]}
id="selectheader"
options={[headers]}
onChange={setJumpLink}
/>
It actually needed:
if (select && select.innerHTML) {
select.innerHTML = '';
}
before the loop.

Auto select options in a <select> based on an array Javascript

I'm working on a project and there is a point which gives me some troubles.
I have a select form autofilled by a script. My select looks up to an array and add the array's values in the select as options.
But now I want to auto select options according to an array.
So I have my array which has some option name inside. Each index correspond to an option. So I would like to select options corresponding to one of the value in the array.
Here is some code :
var attributeFieldCrm = window.parent.Xrm.Page.getAttribute(fieldcrm);
var checkFieldCrmValue = attributeFieldCrm.getValue();
if (checkFieldCrmValue != null) {
console.log('breakpont hit !!!');
var optionSelected = new Array();
optionSelected = checkFieldCrmValue.split("$#");
console.log('les valeurs ont bien été récupérées : ', optionSelected);
var recceuilDesSelections = "";
var result = [];
var options = select && select.options;
var opt;
for (i in optionSelected) {
}
<select id="selectForm" class="selectpicker" multiple data-live-search="true">
</select>
I imagined something like 2 loop for, one going thought the array and for each index I check every options.
thanks for your help !
regards.
It seems that you didn't provide working code, but still:
var sel = document.getElementById('selectForm');
optionSelected.forEach((o)=>{
for (var i = 0;i < sel.options.length;i++) {
if (o == sel.options[i].value) sel.options[i].selected = true;
}
)}

populating html with javascript array

I am trying to populate html select with javascript array, can you guys help me make this one work below are my codes
external javascript (I have found this code somewhere in the internet)
function setRuleName()
{ var myCars=new Array("Saab","Volvo","BMW");
var sel = document.getElementById("dropping") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = title[i]; // set the value
opt.text = title[i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
html code
<Select onclick="setRuleName();" id="dropping" >
</Select>
Not sure where your title attribute came from, but when looping an array, use a standard for, not a for in
for (var i = 0; i < myCars.length; i++) {
var opt = document.createElement("option"); // Create the new element
opt.value = myCars[i]; // set the value
opt.text = myCars[i]; // set the text
sel.appendChild(opt); // add it to the select
}
Alternative ways to write this code.
function setRuleName(){
var myCars=["Saab","Volvo","BMW"],
sel=document.getElementById("dropping");
for(var a=0,tit;tit=myCars[a];++a){
var opt=document.createElement("option");
opt.value=opt.textContent=tit;
sel.appendChild(opt);
}
}
For internal use (NO POST)
function setRuleName(){
document.getElementById("dropping").innerHTML='<option>'+
["Saab","Volvo","BMW"].join('</option><option>')+
'</option>';
}
to access the value :
console.log(document.getElementById("dropping").selected.textContent);

how do i set selected in Dojo form.select option

Hi there Dojo developers, I have a drop down form.select, and it has few options, how do set an option to be selected. Say I want to have the third option displayed in the select element. I was looking at the dojo docs and I do not see setSelected() or similar.
Thanks
You need to use displayedValue property in addition to value to set the displayed option. Use something like:
selector.set("displayedValue", "the_text_of_the_option");
or you can search the underlying store of your drop down by using :
selectorStore.fetch({query:{id: value}, onComplete: function (items) {
dojo.forEach(items, function(item){
selector.set("displayedValue", "the_text_of_the_option");
selector.set("value", "the_value_of_the_option");
});
}});
Hope that helps.
I found it, it is selector.attr("value", "the_name_of_the_option");
Thank you, this is true and working. I have tested it. However i discovered my bug: I was creating the options dynamically, and when I set .selected = true as soon as I add it to the selector it changes the sated to the first one being selected.
Or if I apply selector.set("displayedValue", "the_text_of_the_option");
It displays visually the selected one but in fact behind the selected is still the first one does not meter if I change it with the above selector.set. So I solved it by manually creating the selected state. This way when I add it letter id stays in the desired one and changes it accordingly.
Snipped here:
//populate latitude selector
match = false;
optionsArr = [];
for(var i = 0; i < namesLength; i++){
for(var j = 0, len2 = latNames.length; j < len2; j++){
if(fieldNames[i].toLowerCase() == latNames[j]){
for (var a = 0; a < namesLength; a++) {
var option = {};
option.label = fieldNames[i];
option.value = i+"";
if(i==a){
option.selected = true;
}
optionsArr.push(option);
}
match = true;
}
}
}
if(match){
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(optionsArr);
}else{
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(options);//options is an array of options created originally
}

Categories

Resources