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
Related
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>
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.
I am trying to fill a selectlist with javascript :
for (i=0; i<10; i++)
{
formulaire.choixType[i].options.length= 10;
formulaire.choixType[i].options[i].value =i;
formulaire.choixType[i].options[i].text =i;
}
i have 10 selectlist (K from 0 to 9):
<div>
<select name="choixType[k]" id="choixType" >
<option value="" selected="selected">---choose-</option>
</select>
</button>
</div>
how can i do this , thank you for helping
I have created an exemple here: https://jsfiddle.net/xctty5bd/1/
// get select element with id 'choixType'
var select = document.getElementById('choixType');
for (var i = 0; i < 10; i++) {
// first you create the element <option></option>
var option = document.createElement('option');
// then you add value and text
option.value = i;
option.text = i;
// and then you put option at the end of your select
select.appendChild(option);
}
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>
I've got the following select menu (jsFiddle):
<select>
<option value="volvo">Cars</option>
<option value="saab">------------</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Using Javascript, how would I re-sort the list alphabetically, excluding the first 2 options (Cars and -------), which must remain at the top? Thanks in advance for any help.
Being a purist, I would say that at no point was jQuery specifically mentioned or asked for, it may not be in use in this project for one reason or another. Here's an example using pure javascript.
function sortlist(){
var cl = document.getElementById('carlist');
var clTexts = new Array();
for(i = 2; i < cl.length; i++){
clTexts[i-2] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value + "," +
cl.options[i].selected;
}
clTexts.sort();
for(i = 2; i < cl.length; i++){
var parts = clTexts[i-2].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
if(parts[3] == "true"){
cl.options[i].selected = true;
}else{
cl.options[i].selected = false;
}
}
}
sortlist();
http://jsfiddle.net/GAYvL/7/
Updated to be case neutral.
My first approach was similar to Koolinc's, using Array.prototype.slice to convert the <select> element's children NodeList to an array. However, this doesn't work in Internet Explorer 8 and lower so I changed it to extract, sort and then re-insert:
var sel = document.getElementsByTagName("select")[0],
opts = [];
// Extract the elements into an array
for (var i=sel.options.length-1; i >= 2; i--)
opts.push(sel.removeChild(sel.options[i]));
// Sort them
opts.sort(function (a, b) {
return a.innerHTML.localeCompare(b.innerHTML);
});
// Put them back into the <select>
while(opts.length)
sel.appendChild(opts.shift());
Working demo: http://jsfiddle.net/3YjNR/2/
This is just a more generic answser based on #Jeff Parker's one!
function sortSelect(select, startAt) {
if(typeof startAt === 'undefined') {
startAt = 0;
}
var texts = [];
for(var i = startAt; i < select.length; i++) {
texts[i] = [
select.options[i].text.toUpperCase(),
select.options[i].text,
select.options[i].value
].join('|');
}
texts.sort();
texts.forEach(function(text, index) {
var parts = text.split('|');
select.options[startAt + index].text = parts[1];
select.options[startAt + index].value = parts[2];
});
}
I have also created a fiddle; http://jsfiddle.net/4u86B/1/
I would start by giving a class name to all of the entries I want to sort, and giving and ID to the select:
<select id="sortableCars">
<option value="volvo">Cars</option>
<option class="sortMe" value="saab">------------</option>
<option class="sortMe" value="volvo">Volvo</option>
<option class="sortMe" value="saab">Saab</option>
<option class="sortMe" value="mercedes">Mercedes</option>
<option class="sortMe" value="audi">Audi</option>
</select>
as for the javascript
var mylist = $('#sortableCars');
var listitems = mylist.children('option.sortMe').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });