2nd dropdown options determined by 1st dropdown [duplicate] - javascript

I need to change the contents of dropdown B based on the selection in dropdown A using javascript. There are no db queries involved--I know beforehand what the contents of B should be given the choice in A. I have found some examples using AJAX, but since there is no db query involved that's not necessary. Can anyone point me to some example code for how to do this?

function configureDropDownLists(ddl1, ddl2) {
var colours = ['Black', 'White', 'Blue'];
var shapes = ['Square', 'Circle', 'Triangle'];
var names = ['John', 'David', 'Sarah'];
switch (ddl1.value) {
case 'Colours':
ddl2.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(ddl2, colours[i], colours[i]);
}
break;
case 'Shapes':
ddl2.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(ddl2, shapes[i], shapes[i]);
}
break;
case 'Names':
ddl2.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(ddl2, names[i], names[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
<select id="ddl2">
</select>

Setup mine within a closure and with straight JavaScript, explanation provided in comments
(function() {
//setup an object fully of arrays
//alternativly it could be something like
//{"yes":[{value:sweet, text:Sweet}.....]}
//so you could set the label of the option tag something different than the name
var bOptions = {
"yes": ["sweet", "wohoo", "yay"],
"no": ["you suck!", "common son"]
};
var A = document.getElementById('A');
var B = document.getElementById('B');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function() {
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for (var i in bOptions[_val]) {
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
<select id='A' name='A'>
<option value='yes' selected='selected'>yes
<option value='no'> no
</select>
<select id='B' name='B'>
</select>

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice

Related

Passing a variable from a Select Value to a document.querySelectorAll(Variable here)

I want to be able to select a value from a Selector dropdown on an HTML page and have the 'Value' passed to the document.querySelectorAll() on the .js page. Tried many different variations and it's just not happening.
<div class="custom-select">
<select id="selected" onchange="changeKey()">
<option value="0">Select Key:</option>
<option value="aminorpenta">A</option>
</select>
</div>
Var aminorpenta = [".ANat",".CNat",".DNat",".ENat",".GNat"];
function changeKey() {
var elements = document.querySelectorAll(variable goes here), i;
for (i = 0; i < elements.length; ++i) {
elements[i].style.backgroundColor = "yellow";
elements[i].style.color = "black";
alert(dayVal);
}
}
Use a map of values in standard Javascript object notation.
You can retreive values from an object using a dynamic key by using square bracket notation.
const myObject = {
aminorpenta: [".ANat",".CNat",".DNat",".ENat",".GNat"],
// more key: value pairs
}
function changeKey() {
const selectElement = document.getElementById("selected");
const selectedValue = selectElement.options[selectElement.selectedIndex].value;
const elements = document.querySelectorAll(myObject[selectedValue])
for (i = 0; i < elements.length; ++i) {
elements[i].style.backgroundColor = "yellow";
elements[i].style.color = "black";
}
}
Edited.

Cannot read property 'undefined' of undefined? why this error is coming?

var select = document.getElementById("source");
var select2= document.getElementById("status");
var option = ["1", "2", "3", "4", "5","6","7","8","9"];
var option2= [];
function moveright() {
var a = source.options[source.selectedIndex].value;
var option = document.createElement("option");
option.text = a;
select2.add(option);
select.remove(i);
}
function moveleft() {
var b = status.option2[status.selectedIndex].value;
var option2 = document.createElement("option");
option2.text = b;
select.add(option2);
select2.remove(i);
}
for(i = 0; i < option.length; i++) {
var opt = option[i];
var a = document.createElement("option");
a.innerHTML = opt;
a.value = opt;
select.appendChild(a);
}
for(i = 0; i < option2.length; i++) {
var opt2 = option2[i];
var a = document.createElement("option");
a.innerHTML = opt2;
a.value = opt2;
select2.appendChild(a);
}
<select id = "source" multiple size = "10" onclick = "moveright ()">
<option>Choose a number</option>
</select>
<select id = "status" multiple size = "10" onclick = "moveleft ()">
<option>Choose a number </option>
</select>
I am new to JavaScript I am trying to push the drop down values from one drop down to another. First drop down is working, but second drop down is not working. Can anyone help me? I tried only in the JavaScript array.
Slightly changed, but giving you expected results ;)
Working fiddle
In your moveright and moveright you had a variable i which was not defined. I assume you wanted to use selected option index to remove itself.
And you should write full selector for getting elements, not using it's id directly. Browser picked up source id and returned as html element, however it could not do that with status, because there is such property as window.status.

how to append option to a select

I have a variable which contains a number. I'd like to append an option with the numeric value in each based on whatever the variable number is ( ie: if total equals 10, then I need to add 10 options to the select with each option containing the next numeric row value, so 1, 2, 3, 4...etc. I start off with one hard coded option, and then I need to add options dynamically for every case. I've tried a multitude of scripts but I"m getting " cannot use in operator to search for length.
https://jsfiddle.net/v1yyhfm8/
HTML
<select id="main">
<option selected>1</option>
</select>
I tried:
var total = dataSource.total();
for (var i = 1; 1 <= total; i++) {
var added = document.createElement('option');
var test = $('#main');
added.value = i;
added.innerHTML = i;
test.append(added);
}
and
var total = dataSource.total();
$.each(total, function (i, item) {
$('#main').append($('<option>', {
value: item.total,
text: item.text
}));
});
In your code, the for loop condition would be true always which leads to an infinite loop so change it to i <= total.
var total = dataSource.total();
for (var i = 1; i <= total; i++) {
var added = document.createElement('option');
var select1 = $('#main');
added.value = i;
added.innerHTML = i;
select1.append(added);
}
var total = 10;
for (var i = 1; i <= total; i++) {
var added = document.createElement('option');
var select1 = $('#main');
added.value = i;
added.innerHTML = i;
select1.append(added);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="main">
<option selected>1</option>
</select>
Html part :
<select id="main">
</select>
Jquery Part:
var opt = ' <option selected>1</option>';
for(var i = 2; i<= 10; i++){
opt += ' <option>' + i + '</option>';
}
$("#main").append(opt);
Jsfiddle link : https://jsfiddle.net/v1yyhfm8/

Why won't the addEventListener trigger on change?

Trying to get the eventlistener to run, i.e. when I select United Kingdom, another selection box will appear to select county (county() function), but for some reason the addEventListener will not call the function, and I can't fathom how to pass the selected country to the county function? Any ideas please.
function countries() {
xmlRequest("countries.xml");
var country_selector = document.createElement("SELECT");
country_selector.id = "cou n tryselection";
document.getElementById("quiz").appendChild(country_selector);
var t = document.getElementById("countryselection");
var c_opt = document.createElement("option");
c_opt.text = "Please select";
c_opt.selected = true;
t.add(c_opt);
c_opt = document.createElement("option");
c_opt.text = "United Kingdom";
c_opt.value = "1";
t.add(c_opt);
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
var x = xmlDoc.getElementsByTagName("country");
for (i = 0; i < x.length; i++) {
var opt = document.createElement("option");
opt.text = x[i].getElementsByTagName("country_name ")[0].childNodes[0].nodeValue;
t.add(opt);
}
}
function county(Country) {
if (!document.getElementById("countyselection")) {
if (Country === "1") {
xmlRequest("counties.xml");
document.getElementById("quiz").innerHTML += "<select id='countyselection'></select>";
var t = document.getElementById("countyselection");
var y = xmlDoc.getElementsByTagName("county");
for (j = 0; j < y.length; j++)
{
var opt = document.createElement("option");
var txt = y[j].getElementsByTagName("county_name")[0].childNodes[0].nodeValue;
opt.text = txt;
t.add(opt);
}
}
} else {
var f = document.getElementById("countyselection");
document.getElementById("countyselection").parentNode.removeChild(f);
}
}
Because you're calling the function, not referencing it, and you have a space in the function name.
change
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
to
document.getElementById("countryselection").addEventListener("change", function() {
county(this.value);
}, false);
Also note that things like this
country_selector.id = "cou n tryselection";
is completely invalid, you can't use random text with spaces as an ID

How to show <Select > in sorted order

How can I sort the <option> elements of a <select> tag using JavaScript?
Here is the HTML I have:
<form action="example.asp">
<div>
<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>
</select>
</div>
</form>
If the value is different than the text, use the following function to sort both of them. This is just an updated version of above solution and will keep both the name and associated value.
<script language="JavaScript" type="text/javascript">
function sortList()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
arrValues[i] = lb.options[i].value;
arrOldTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
</script>
<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
<form action="#">
<select name=mylist id=mylist size=5>
<option value="Anton">Anton
<option value="Mike">Mike
<option value="Peter">Peter
<option value="Bill">Bill
<option value="Carl">Carl
</select>
<br>
sort
</form>
You should think about it on the pre html-creation level. If you are generating them from some kind of list or by dynamic page mechanism then sort them before you generate your option elements - thats the clearest way ;)
A simpler solution, building on Yasir Al-Agl's answer:
function sortList()
{
var lb = document.getElementById('mylist');
arr = new Array();
for(i = 0; i < lb.length; i++) {
arr[i] = lb.options[i];
}
arr.sort(function(a,b) {
return (a.text > b.text)? 1 : ((a.text < b.text)? -1 : 0);
}); // or use localeCompare() if you prefer
for(i = 0; i < lb.length; i++) {
lb.options[i] = arr[i];
}
}
In short, you need only one Array, the elements of which are simply references to the original "options" Objects. The sort() function also has the freedom to choose which option property to sort on (ie, the text property, the value property, etc).
Don't forget, however, that the "selectedIndex" property of the "select" control may no longer be correct after the sort.
This function works as in the last answer, but also keeps the selection of item
// Sorts all entries of a select item (= dropdown) by their visible name, keeping the internal values and the selection
function sortSelectEntries(selItem) {
let formerSel = selItem.value;
let count = selItem.length;
let options = new Array();
for (var i = 0; i < count; i++)
options[i] = selItem.options[i];
options.sort((e1, e2) => e1.text > e2.text ? 1 : (e1.text < e2.text ? -1 : 0));
for (i = 0; i < count; i++)
selItem.options[i] = options[i];
selItem.value = formerSel; // restore selection
}

Categories

Resources