Why does removeChild() not work in select option - javascript

var arr = {'ukraine' : ['Киев', 'Одесса', 'Харьков'], 'russia' : ['Петербург', "Москва", "Архангельск"], 'belarus' : ['Минск', 'Витебск', 'Гомель']};
var countries = document.getElementById('country');
var cities = document.getElementById('cities');
cities.style.visibility = 'hidden';
countries.addEventListener('change', func);
function func(){
var temp = countries.value;
var city = arr[temp];
if(cities.options != undefined){
for(var i = 0; i < cities.options.length; i++){
alert(i);
cities.removeChild(cities.options[i]);
}
}
for(var i = 0; i < city.length; i++){
var option = document.createElement('option');
option.innerHTML = city[i];
cities.appendChild(option);
}
cities.style.visibility = 'visible';
}
These russian words mean cities. What I'm trying to do is to display second select depending on the option I choose in the first one. But when I'm trying to delete all old options of cities select, it just deletes the first option, even though I put it in the loop? Why does removeChild only work for the first child?

Related

Javascript Run one click then another

What I'm trying to do is make it open the breed_selector dropdown menu, and then select breed1, then .click, then move onto the next breed and click, and continue, It needs to do this three times, but unfortunately it only selects the first breed of dog and clicks, not all three.
Thanks
(function() {
var x = document.getElementById("breed_selector).options;
for(var i=0;i<x.length;i++){
if(x[i].text=="Labrador"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
}
}
var x = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
if(x[i].text=="poodle"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
})();
At the moment, it just doesn't do anything,
I have tried
var = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
if(x[i].text=="poodle", "Labrador", "pug"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
But the above doesn't work either, any input would be great, Thanks :)
UPDATED CODE which still doesn't work
(function() {
var x = document.getElementById("breed_selector").options;
for(var i=0;i<x.length;i++){
var text = x[i].text;
if(x[i].text === "Labrador" && text === "Pug"){
x[i].selected=true;
document.getElementsByClassName("shop")[0].click();
break;
}
}
})();
You could try this to click on ALL the options of the select element:
var breedSelector = document.getElementById("breed_selector");
var howMany = breedSelector.length;
var buttonShop = document.querySelector(".shop");
for (var i = 0; i < howMany; i++) {
breedSelector.selectedIndex = i;
buttonShop.click();
}
Note, though, that it will click the button several times in quick succession.
In order to select only certain options based on their value, you could try something like:
var breedSelector = document.getElementById("breed_selector");
var whichOnes = ["Labrador", "Poodle", "Golden"]; //whichever you want.
var buttonShop = document.querySelector(".shop");
whichOnes.forEach(function(breed){
breedSelector.selectedIndex = [].findIndex.call(breedSelector, function(option) { return option.textContent == breed});
buttonShop.click();
}

How to display JSON objects as options of a dropdown in HTML, using a common JavaScript funciton for all objects

I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!

Dynamically Generating Dropdown options

I need help with this dynamically generated dropdown options. What I am trying to accomplish is have three dynamically generated dropdown menus that are dependent on each other. I can get the first dropdown to be created just fine, but my main issue is that I cannot get the onchange to fire when something new is selected.
var dropDown = document.createElement("FIELDSET");
var course_s = document.createElement("SELECT");
course_s.id = "course";
for(var j = 0; j < courseList.length+1; j++){
var course_o = document.createElement("OPTION");
if(j == 0){
course_o.value = "NONE";
course_o.innerHTML = "NONE";
}else{
course_o.value = courseList[j-1];
course_o.innerHTML = courseTitle[j-1]+" "+courseNumber[j-1];
}
course_s.appendChild(course_o);
}
var module_s = document.createElement("SELECT");
module_s.id = "module";
var module_o = document.createElement("OPTION");
module_o.value = "NONE";
module_o.innerHTML = "NONE";
module_s.appendChild(module_o);
var segment_s = document.createElement("SELECT");
segment_s.id = "segment";
var segment_o = document.createElement("OPTION");
segment_o.value = "NONE";
segment_o.innerHTML = "NONE";
segment_s.appendChild(segment_o);
Module and segment options are set when course has been changed.

Populating dropdownlist values based on another dropdown using javascript

I'm doing this on the jsp page of another application. I need to populate values on combobox based on another combo box. I've seen several posts explaining this but can't make it to work for myself.
Here's what I tried.
<script type="text/javascript">
function customChangefunction(){
var target = window.document.getElementsByName("resultCombo");
var src = window.document.getElementById("sampleCombo");
var strUser = src.options[src.selectedIndex].value;
alert(strUser);
var colours = new Array('Black', 'White', 'Blue');
var shapes = new Array('Square', 'Circle', 'Triangle');
var names = new Array('John', 'David', 'Sarah');
switch (strUser) {
case 'one':
target.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(target, colours[i], colours[i]);
}
break;
case 'two':
target.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(target, shapes[i], shapes[i]);
}
break;
case 'three':
target.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(target, names[i], names[i]);
}
break;
default:
target.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement("OPTION");
opt.value = value;
opt.text = text;
ddl.options.add(opt);
opt.appendChild(text);
document.getElementById(ddl).appendChild(opt);
}
The above code is not working.I have to do this without using jquery.
My actual requirement is
if Combo1 is India then Combo2 should show Chennai,Delhi,Mumbai
if Combo1 is USA then Combo2 should show New York,CA,etc..
I have one more question. Suppose that Combo2 is already having some values does this replace those with these values.I would like to do this way
Please comment on this before you mark this question as duplicate or closing it.
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}

How do i place a list of values onto a drop down ?? (must use DOMs, no jquery)

i'm trying to place a list of items onto a dropdown box but having little success. I have my list of items labelled MARKET, and i have a drop box using the "select" element, i've been trying all sorts of elements like .value and .option and .setAttribute but i dont know how to formulate the code using them, if there are any other elements i should be looking at then i would certainly like to know for future reference, but for the moment i would like to know how i can change my code so i can put a list of items onto a dropdown box !! Appreciate the help if there is any !!
var lbldiv = document.createElement("div");
var mklbl = document.createElement("label");
mklbl.innerHTML = "Market ";
var mkslct = document.createElement("select"); //dropdown
lbldiv.appendChild(mklbl);
lbldiv.appendChild(mkslct);
document.body.appendChild(lbldiv);
var markets = ["UK", "USA", "China"]; //list of markets
var mkul = document.createElement("ul"); //formulated list
mkul.className = "mkul";
for(var i = 0; i < markets.length; ++i){
var crtli = document.createElement("li");
crtli.value = i;
crtli.innerHTML = markets[i];
mkul.appendChild(crtli);
}
document.body.appendChild(mkul);
function populateDDLB() {
var selectEl = document.getElementById("dropdownlistbox");
var options = ["A", "B", "C", "D"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
selectEl.appendChild(el);
}
}
window.onload = populateDDLB;

Categories