Changing JavaScript array values - javascript

I've been following this guide on w3schools to dynamically change the elements of a dropdown select based off another dropdown select, as seen below:
The code to do this is as follows:
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>
However, I noticed that for the second dropdown select, the element's values are numbered, and I was wondering how to change those values into text.
Eg. in the linked example the first select is as follows:
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
And if I set the value of the first select to Volvo, the second select is as follows:
<select id="carmodel">
<option value="1">V70</option>
<option value="2">XC60</option>
<option value="3">XC90</option>
</select>
What I would like to obtain compared to above:
<select id="carmodel">
<option value="V70">V70</option>
<option value="XC60">XC60</option>
<option value="XC90">XC90</option>
</select>

Replace var car = new Option(cars[i], i) with var car = new Option(cars[i], cars[i])
DEMO :
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], cars[i]);
modelList.options.add(car);
}
}
}
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>

You can do this easily using a PHP/MySQL/Ajax and store them in a database, however if you don't want to use any serverside programming, you can set a data-* global attribute for each of your option tags:
data-option="Car model name here"
Read more about "data-*" on W3Schools: https://www.w3schools.com/tags/att_global_data.asp

Here are two options for you:
Change the constructor:
var car = new Option(cars[i], cars[i]);
Or
var car = new Option(cars[i]);
car.value = cars[i];
Just after the constructor.
The problem you are facing is caused by the second argument in the constructor of the Option object, which gives the value of the option element.

Related

Assign values to dropdown option from javascript varaibles?

I have a dropdown with four option. I want to assign values to dropdown from javascript.
<select class="dropwdown-test" id="dropTest">
<option>Person 1</option>
<option>Person 2</option>
<option>Person 3</option>
<option>Person 4</option>
</select>
These are four variables that need to assigned to option values from a function() or function(response).
var p1 = 'john'
var p2 = 'marcus'
var p3 = 'anthony'
var p4 = 'aaron'
You can do something like below:
document.addEventListener('DOMContentLoaded', (event) => { // on DOM loaded
var p1 = 'john';
var p2 = 'marcus';
var p3 = 'anthony';
var p4 = 'aaron';
var list = [p1, p2, p3, p4]; // put the variables in a list
var select = document.getElementById("dropTest"); // get the select
var options = select.querySelectorAll("option"); // get it's options
options.forEach(function(el, i) {
if(list[i]) { // if list has element list[i]
el.value = list[i]; // assign option value to list[i]
// commenting out because OP wants only values assigned and not innerHTML
// el.innerHTML = list[i]; // assign option innerHTML to list[i]
}
});
})
<select class="dropwdown-test" id="dropTest">
<option>Person 1</option>
<option>Person 2</option>
<option>Person 3</option>
<option>Person 4</option>
</select>

Set Select in Alphabetical Order with Javascript

I have a project where I need to set the select options in alphabetical order. Here's my HTML code:
<select id=”carmakes”>
<option value="Volvo">Volvo</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
<option value="Saab">Saab</option>
</select>
And here is my script:
function alphabeticalOrder() {
let value = document.getElementsByTagName("select")[0];
for (let i = 0; i < value.children.length - 1; i++) {
if (value.children[i].innerHTML < value.children[i + 1].innerHTML) {
let temp = value.children[i].innerHTML;
value.children[i].innerHTML = value.children[i + 1].innerHTML;
value.children[i + 1].innerHTML = temp;
}
}
return value;
}
I've tried using sort but I couldn't seem to get it to work.
As scunliffe mentioned, it's best to start with the values in JS rather than in HTML in this case. Try this:
const makes = [
'Volvo',
'Mercedes',
'Audi',
'Saab'
];
const sortedMakes = makes.sort((a,b) => {
if (a === b)
return 0;
if (a < b)
return -1;
return 1;
});
const selectEl = document.getElementById('carmakes');
for(const make of sortedMakes) {
const newOpt = document.createElement('option');
newOpt.value = make;
newOpt.innerHTML = make;
selectEl.appendChild(newOpt);
}
<select id="carmakes"></select>
If you must sort it with the values starting in HTML, you can do it like this:
const selectEl = document.getElementById('carmakes');
const makes = Array.from(selectEl.getElementsByTagName('option'))
.map(el => el.innerText);
const sortedMakes = makes.sort((a,b) => {
if (a === b)
return 0;
if (a < b)
return -1;
return 1;
});
while(selectEl.firstChild) {
selectEl.firstChild.remove();
}
for(const make of sortedMakes) {
const newOpt = document.createElement('option');
newOpt.value = make;
newOpt.innerHTML = make;
selectEl.appendChild(newOpt);
}
<select id="carmakes">
<option value="Volvo">Volvo</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
<option value="Saab">Saab</option>
</select>

Javascript Form Select Change Options Dynamic List/ one to multiple lists

trying to make one Select change option control multiple select options. Select the first option where following options are associated with choices for first option. I entered the third line but the second line does not work and the third line receives the select the the two would.
<script>
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var s3 = document.getElementByis(s3);
s2.innerHTML = "";
s3.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
} else if(s1.value == "Dodge"){
var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
s3.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2','slct3')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />
Choose Car Model:
<select id="slct3" name="slct3"></select>
</body>
First of all, looks that there are some typos in your code.
function populate(s1,s2){ //missing parameter 's3'
...
var s3 = document.getElementByis(s3) //Should be getElementById
...
Given that to append the new option node you created inside your for loop, you should use the appendChild function. But since you can't append the same node twice in your DOM, you can use the cloneNode function.
Then you replace the lines:
...
s2.options.add(newOption);
s3.options.add(newOption);
...
With:
...
var dup = newOption.cloneNode(true); // check the docs for the 'true' parameter here
s2.appendChild(newOption);
s3.appendChild(dup);
...
Working Fiddle:
<script>
function populate(s1,s2,s3){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var s3 = document.getElementById(s3);
s2.innerHTML = "";
s3.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
} else if(s1.value == "Dodge"){
var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
var dup = newOption.cloneNode(true);
s2.appendChild(newOption);
s3.appendChild(dup);
// s2.options.add(newOption);
// s3.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2','slct3')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />
Choose Car Model:
<select id="slct3" name="slct3"></select>
</body>

HTML Select tag too big

I basically have this hard-coded:-
<select id="nr">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
It is supposed to select a value from an array, is there a way I can make a select without hard coding all those values? Preferably creating one with a loop with the length of my array in javascript or html?
Hope this helps you!
function addOptionValue(value) {
var option = document.createElement('option');
option.setAttribute('value', value);
option.innerHTML = value;
selectEl.appendChild(option);
}
var optionsArray = [1, 2, 3, 4, 5],
selectEl = document.getElementById('nr');
for (i in optionsArray) {
addOptionValue(optionsArray[i]);
}
<select id="nr"></select>
something like this?
var arr = [0,1,2,3,4,5];
var select_elem = document.getElementById("nr");
for (var i = 0; i < arr.length; i++){
var option = document.createElement("option");
option.value = arr[i];
option.text = arr[i];
select_elem.appendChild(option)
}
<select id="nr">
</select>
Jquery
$(function(){
for (i=1;i<=5;i++){
$("#nr").append($('<option></option>').val(i).html(i))
}
});
Javascript
<script>
for(var i=1; i<=5; i++){
var option = document.createElement("option");
option.value = i;
option.text = i;
document.getElementById('nr').appendChild(option);
}
/<script>
Demo

2 dropdown lists connected to each-other (the 2nd one depends from the first)

I am trying to solve an exercise with these demands : "Create a HTML page also using javascript who contains a dropdown list where u choose the State and another dropdown list is filled dynamically with cities belonging to that Country.
I have seen other similar questions and applied the suggestions but it still doesnt seem to work (the 2nd dropdown list stays empty).
<html>
<head>
<script type = "text/javascript">
function update()
{
var albania = ["Tirana","Durres","Vlore","Shkoder"];
var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
var germany = ["Berlin","Frankfurt","Hannover","Bonn"];
var countries = document.getElementById("1");
var cities = document.getElementById("2");
var selected = countries.options[countries.selectedIndex].value;
if(selected=="1"){
for(var i = 0; i < albania.length; i++) {
var opt1 = document.createElement('option');
opt1.innerHTML = albania[i];
opt1.value = albania[i];
cities.appendChild(opt1);
}
}
else if(selected=="2")
{
for(var j = 0; j < kosovo.length; j++) {
var opt2 = document.createElement('option');
opt2.innerHTML = kosovo[j];
opt2.value = kosovo[j];
cities.appendChild(opt2);
}
}
else if(selected=="3")
{
for(var k = 0; k < germany.length; k++) {
var opt3 = document.createElement('option');
opt3.innerHTML = germany[k];
opt3.value = germany[k];
cities.appendChild(opt3);
}
}
else
var t =0;
}
</script>
</head>
<body>
<p><select id= "1" onchange="update()">
<option selected = "selected" >Select Country</option>
<option value="1">Albania</option>
<option value="2">Kosovo</option>
<option value="3">Germany</option>
</select>
</p>
<p><select id="2">
<option selected = "selected" ></option>
</body>
</html>`"
Here is Working Example as per your requirement.
Javascript :
var albania = ["Tirana","Durres","Vlore","Shkoder"];
var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
var germany = ["Berlin","Frankfurt","Hannover","Bonn"];
document.getElementById("1").addEventListener("change", function(e){
var select2 = document.getElementById("2");
select2.innerHTML = "";
var aItems = [];
if(this.value == "2"){
aItems = kosovo;
} else if (this.value == "3") {
aItems = germany;
} else if(this.value == "1") {
aItems = albania;
}
for(var i=0,len=aItems.length; i<len;i++) {
var option = document.createElement("option");
option.value= (i+1);
var textNode = document.createTextNode(aItems[i]);
option.appendChild(textNode);
select2.appendChild(option);
}
}, false);
HTML :
<p><select id= "1">
<option selected = "selected" >Select Country</option>
<option value="1">Albania</option>
<option value="2">Kosovo</option>
<option value="3">Germany</option>
</select>
</p>
<p><select id="2">
<option selected = "selected" ></option></select></p>
Try this:
<html>
<head></head>
<body>
<p>
<select id="country" onchange="update()">
<option selected="selected">Select Country</option>
<option value="1">Albania</option>
<option value="2">Kosovo</option>
<option value="3">Germany</option>
</select>
</p>
<p>
<select id="city">
<option selected="selected">Select City</option>
</select>
</p>
<script type="text/javascript">
function update()
{
var albania=["Tirana", "Durres", "Vlore", "Shkoder"];
var kosovo=["Prishtina", "Mitrovica", "Peje", "Gjakove"];
var germany=["Berlin", "Frankfurt", "Hannover", "Bonn"];
var countries=document.getElementById("country");
var cities=document.getElementById("city");
var selected=countries.value;
var html='<option selected="selected">Select City</option>';
if(selected === "1")
{
for(var i=0; i < albania.length; i++)
{
html+='<option value="' + albania[i] + '">' + albania[i] + '</option>';
}
}
else if(selected === "2")
{
for(var j=0; j < kosovo.length; j++)
{
html+='<option value="' + kosovo[j] + '">' + kosovo[j] + '</option>';
}
}
else if(selected === "3")
{
for(var k=0; k < germany.length; k++)
{
html+='<option value="' + germany[k] + '">' + germany[k] + '</option>';
}
}
cities.innerHTML=html;
}
</script>
</body>
</html>
Javascript:
<script type="text/javascript">
function update() {
//Add additional country with id and city array
var countriesArray = [
["albania", "1", ["Tirana", "Durres", "Vlore", "Shkoder"]],
["kosovo", "2", ["Prishtina", "Mitrovica", "Peje", "Gjakove"]],
["germany", "3", ["Berlin", "Frankfurt", "Hannover", "Bonn"]]
];
//Get country dropdown
var countries = document.getElementById("1");
//Get city dropdown
var cities = document.getElementById("2");
//Get country selected item
var selected = countries.options[countries.selectedIndex].value;
//If country is not "Select Country"
if (selected != "0") {
//Clear previous cities - this can be moved outside of if condition, and remove the else, if wanted.
Clear(cities);
//For each country, if it is selected, populate the cities dropdown with its associated city array.
var country;
var cityArray;
for (var i = 0; i < countriesArray.length; i++) {
//Get country
country = countriesArray[i];
if (country[1] == selected) {
//Get city array
cityArray = country[2];
//Populate options with city array
for (var p = 0; p < cityArray.length; p++) {
var opt1 = document.createElement('option');
opt1.innerHTML = cityArray[p];
opt1.value = cityArray[p];
cities.appendChild(opt1);
}
}
}
}
else
{
Clear(cities);
}
}
function Clear(ctrl)
{
ctrl.options.length = 1;
}
</script>
HTML:
<p>
<select id="1" onchange="update()">
<option value="0" selected="selected">Select Country</option>
<option value="1">Albania</option>
<option value="2">Kosovo</option>
<option value="3">Germany</option>
</select>
</p>
<p>
<select id="2">
<option value="0" selected="selected">Select City</option>
</select>
</p>

Categories