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>
Related
with vanilla javascript I'd like to loop through my dropdown, and change the selected one, and then change the text that is displayed. I have it selecting, but I'm not getting the object name correct to change the optionText? of the item.
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
i.options.text = "Edgewood Login"; //This is WRONG
break;
}
}
guidance is appreciated.
You can use a querySelector and a selector to access it without a loop.
v = "222";
selProvider = document.querySelector("#membershipProvider option[value='" + v + "']");
if (selProvider) {
selProvider.text = "CHANGED!";
selProvider.selected = true;
}
<select id="membershipProvider">
<option value='111'>AAA</option>
<option value='222'>BBB</option>
</select>
You need to modify the option at that index. Right now you are trying to modify the index itself.
should be:
dd.options[i].text
not
i.options.text
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
dd.options[i].text = "Edgewood Login"; //This is WRONG
break;
}
}
<select id="membershipProvider">
<option value="cifs">CIFS</option>
<option value="LdapUsers">LdapUsers</option>
<option value="nfs">NFS</option>
<option value="test">Test</option>
</select>
You should use
dd.options[i].text = "Edgewood Login";
just like when checking for its value
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
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); });
I have a couple select elements:
<select name="empID" onchange='setSupervisor(this);'>
<option value="111" sid="222">Eric Employee</option>
...
</select>
<select name="supervisorID">
<option value="333">Susie Supervisor</option>
<option value="222">Stan Supervisor</option>
</select>
And a javascript function:
function setSupervisor(sender)
{
??
}
How can I set the supervisor dropdown after the user selects from the employee dropdown? The tricky part here (at least to me) is having to use a custom sid and not the value from the employee dropdown.
function setSupervisor(sender) {
var selectedOption = sender.getElementsByTagName("option")[sender.selectedIndex];
var sid = selectedOption.getAttribute("sid");
var supervisorSelect = document.getElementsByName("supervisorID")[0];
for (var i = 0, len = supervisorSelect.options.length, option; i < len; ++i) {
option = supervisorSelect.options[i];
if (option.value == sid) {
option.selected = true;
return;
}
}
}
Try this:
var empID = document.getElementsByName("empID").item(0);
var supervisorID = document.getElementsByName("supervisorID").item(0); //This becomes a bit easier if you set an ID as well as a name in your HTML
var index = empID.selectedIndex;
var sid = empID.options[index].getAttribute("sid");
for(var i=0; i<supervisorID.options.length; i++)
{
if(supervisorID.options[i].value == sid)
{
supervisorID.selectedIndex = i;
break;
}
}