Dynamic drop down menu will not create based on selection - javascript

So i'm working on a project that creates three drop down menus that appear based on the option selected on the first. When I select from the first menu, "Male" or "Female" the correct menus appear( example, when Male is selected, the drop down with the options ""Human", "Dwarf", "Orc" appear). However, after that I can not get a third drop down menu to appear based on the next selection using the same methods before. At this point I am very lost.
var step1 = ["Choose Gender?", "Male", "Female"];
var step2 = [["Choose your race!", "Human", "Dwarf", "Orc"],["Choose your race!", "Fairy", "Elf", "Centaur"]];
var step3 = [["Human Class!", "Warrior", "Sorcerer", "Theif"], ["Elf Class!", "Cleric", "Necromancer", "Priest"], ["Dwarf Class!", "Cannonner", "Rifelman", "Engineer"], ["Orc Class!", "Beserker","Warlock", "Shaman"], ["Fairy Class!", "Druid", "Arcanist", "Mystic"]];
function testData(){
menuCreate(step3[0]);
}
function init() {
menuCreate(step1);
var dropdown = document.getElementById("form");
dropdown.onchange = function(event){
if (dropdown.value == "Male"){
//menuCreate(step2[0]);
var myDiv = document.getElementById("mainDiv");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
myDiv.appendChild(next);
} else if (dropdown.value == "Female"){
//menuCreate(step2[1]);
myDiv = document.getElementById("mainDiv");
femaleNext = document.createElement('input');
femaleNext.setAttribute('type','button');
femaleNext.setAttribute('value','Next');
femaleNext.setAttribute('onclick','femaleRace()');
myDiv.appendChild(femaleNext);
}
}
} // end init()
function menuCreate(step1){
//console.log(step1);
var myDiv = document.getElementById("mainDiv");
var titleElement = document.createElement("h1");
titleElement.setAttribute('style','color:white');
titleElement.setAttribute('id','guide');
var selectForm = document.createElement('select');
selectForm.id = "form";
myDiv.appendChild(selectForm);
for (var i=0; i< step1.length; i++){
var option = document.createElement('option');
option.value = step1[i];
option.text = step1[i];
selectForm.appendChild(option);
}
} // end menuCreate()
function maleRace(){
menuCreate(step2[0]);
var down = document.getElementById("form");
down.onchange = function(event){
if (down.value == "Human"){
menuCreate(step3[0]);
var div = document.createElement("div");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
div.appendChild(next);
}
}
} // end maleRace()
Please note I cant use JQUERY or innerHTML/innerText. I have to do this using normal JavaScript the problem is that when I select "Human" on the second menu, I am supposed to get another menu that uses step3[0].

In the menuCreate function, you're setting an id attribute to the select element: selectForm.id = "form";. After you call it for the second time (for the second step), you have two elements with the same id in your document. Then, when you try to add the onchange event handler on the maleRace function - document.getElementById("form"); down.onchange = function(event){ you actually attach this handler to the first select element (the gender one) instead of the second one.
A nice way to solve this problem, will be to add a second argument to the menuCreate function like so: function menuCreate(step1, id){. Then, change this line a bit from selectForm.id = "form"; to selectForm.id = id;.
Then, change every call to the createMenu function to have its own id:
function init() {
menuCreate(step1, 'step1form');
var dropdown = document.getElementById("step1form");
function maleRace(){
menuCreate(step2[0], 'step2form');
var down = document.getElementById("step2form");
You can check out this codepen: https://codepen.io/anon/pen/xXJwBv?editors=1011

Related

How to show json in div?

I have two buttons SHOW and HIDE. When show is clicked numbers will appear (which are json files, each json file contain only one number 1, 2, 3..) when HIDE is clicked first number(json) in a row dissapear. For example we clicked SHOW button 3 times and got this: 1 2 3 and then clicked HIDE once then we got: 2 3 shown. My problem is when HIDE is clicked I want to save that hidden number by showing it in my div where id="nome". After another clicking on button HIDE another hidden number is shown and old is deleted from div. I tried this:
var pageCounter = 1;
var pageCounterr = 1;
var animalContainer = document.getElementById("animal-info");
var animalContainerr = document.getElementById("nome");
var btn = document.getElementById("btn");
var btnn = document.getElementById("btnn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://10.0.9.243/animals-'+ pageCounter + '.json');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
};
ourRequest.send();
pageCounter++;
});
function renderHTML(data) {
var htmlString = document.createElement("div");
for (i=0; i < data.length; i++){
let pText = document.createTextNode(data[i].name);
let pElement = document.createElement("p");
pElement.append(pText);
htmlString.append(pElement);
htmlString.classList.add('containers') // new Line added
}
animalContainer.append(htmlString);
}
btnn.addEventListener("click", function(){
let containers = document.getElementsByClassName('containers');
if(containers.length > 0){
document.getElementById("nome").innerHTML = containers[0];
containers[0].remove();
}
});
<button id="btn">SHOW</button>
<button id="btnn">HIDE</button>
<h2>Numbers:</h2>
<div id="animal-info"></div>
<h2>Hidden number is:</h2>
<div id="nome"></div>
And what I get as a result is ' [object HTMLDivElement] ' in div with id="nome".
The only thing that is wrong is the used logic, look this:
When you get elements by class name "container" you are getting a array of this:
var htmlString = document.createElement("div");
Cause you defined that element's class to:
htmlString.classList.add('containers')
Then you're just getting div.
Solution:
Inside of this element you have a "p" element, and inside it you have a textNode with the content that you want!
Simple, good programming for you.

How to dynamically add remove block using javascript

I am facing a problem while removing a paragraph, which I have added using javascript.
Adding buttons work fine. The problem occurs when I try to remove the paragraph.
function rdn_id(){return Math.random().toString(36).substring(7);}
//create button
function create_btn()
{
//Create a remove button
var btn_remove = document.createElement("BUTTON");
//create a unique button ID
id_btn_remove = rdn_id();
btn_remove.id = id_btn_remove ;
btn_remove.textContent = "Remove file";
return [btn_remove, id_btn_remove];
}
//add elt function
function create_p_btn()
{
//Create paragraph
var paragraph = document.createElement("P");
//create a unique p ID
id_paragraph = rdn_id();
paragraph.id = id_paragraph;
paragraph.style.paddingTop = "5px";
paragraph.style.background = "blue";
document.getElementById("setItHere").appendChild(paragraph);
// add button
var values = create_btn();
var btn_rmv = values[0];
var id_btn = values[1];
paragraph.appendChild(btn_rmv);
document.getElementById(id_btn).addEventListener("onclick", function(){remove_func(id_paragraph);});
}
//Remove function
function remove_func(id_el)
{
var elt = document.getElementById(id_el);
elt.parentNode.removeChild(id_el);
}
<div id="setItHere">
<Button id="start" onclick="create_p_btn();">add</Button>
</div>
Am I missing something ?
Thank you in advance.
You need to make two changes:
Event name should be click instead of onclick
elt.parentNode.removeChild(id_el); should be elt.parentNode.removeChild(elt);
Check out this pen
https://codepen.io/tanmayv/pen/yLNwNNJ

jQuery - Is it possible to change selectbox's options during cloning?

Is it possible to change selectbox's options during cloning?
I am cloning a div with its inner children. Each one of them has a different id every time they get cloned. The original div contains a select box which gets it's values from the database.
My question is, is it possible to amend the values of the cloned select boxes so they will not contain the previous selected values? Any tips on how to do this?
What I need is the newly created select boxes won't contain the values of the previous selections.
Example if in select box 1 I choose 1 (from a range 1-10) then the value 1 will not appear in the other select boxes
JS
<script>
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
var original = document.getElementById('duplicator');
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.querySelector('#c_service').setAttribute('id',new_service_ID);
clone.querySelector('#vat').setAttribute('id',new_vat_ID);
clone.querySelector('#amount').setAttribute('id',new_amount_ID);
clone.querySelector('#vat_amount').setAttribute('id',new_vatamount_ID);
original.parentNode.appendChild(clone);
};
</script>
You should keep track of what's selected and regenerate a select from scratch, this would be easier
const selectClass = "mySelect";
const options = [
{id: "c_service", name: "c_service"},
{id: "vat", name: "vat"},
{id: "amount", name: "amount"},
{id: "vat_amount", name: "vat_amount"}
];
var id = 0;
function addSelect() {
// Get selects
let selects = document.getElementsByClassName(selectClass);
// Get all selected values
let selectedOpts = [];
for (let select of selects) {
if (select.value != "") {
selectedOpts.push(select.value);
}
}
// Create the new select
let select = document.createElement("select");
select.setAttribute("class",selectClass);
select.appendChild(document.createElement("option"));
// Get available options
var avOpts = options.filter(o => selectedOpts.indexOf(o.id) == -1);
// Create the options
for (var option of avOpts) {
id++;
let o = document.createElement("option");
o.setAttribute("id", option.id + id);
o.innerHTML = option.name;
select.appendChild(o);
}
// Add the select to DOM
document.getElementById("divToInsertInto").appendChild(select);
}
// add the initial select
addSelect();
// Attach event
document.getElementById('btn_new_service').onclick = addSelect;
<button id="btn_new_service">clone</button>
<div id="divToInsertInto">
</div>

adding an onchange event to select

I have the following js code:
function createConBox() {
var charDiv = document.getElementById("characterList"); // reference to "characterList" div
header = document.createElement("p"); // creates the <p> tag
charDiv.appendChild(header); // adds the <p> tag to the parent node
title = document.createTextNode("Show Only Lines By:"); // creates the text string
header.appendChild(title); // adds the text string to the parent node
// create select box and add elements
selectBox = document.createElement("select");
selectBox.setAttribute("id", "cList");
charDiv.appendChild(selectBox);
charNames = uniqueElemText("h3"); // array of character names
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode("Show All Lines");
newOption.appendChild(newOptionTitle);
for (i = 0; i < charNames.length; i++) {
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode(charNames[i]);
newOption.appendChild(newOptionTitle);
}
}
function showLines() {
alert("The Box has been changed");
}
Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter.
selectBox.onchange = showLines; should solve your problem.
in some browsers onchange get fired only after blurring select box. to over come this you can use onclick instead of onchange
My guess is that you're doing this:
selectBox.onchange = showLines();
If that's the case, just remove the ():
selectBox.onchange = showLines;
When I pass dynamically id in case then what I do:
var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`

How can I create multiple ul-lists dynamically?

I have a <ul> "ul-list-one", which contains a number of checkboxes. If I check the checkbox and click the move button it means that it will move to another <ul> "ul-list-two", and the checked checkbox will be removed from the previous, which here would be "ul-list-one".
In "ul-list-two" I can do the same, and it moves to the next, this time "ul-list-three".
Note: "ul-list-two" and "ul-li-three" will be created dynamically.
Here I have done some work, but how can I be able to create multiple <ul>s dynamically?
$('#mer').click( function() {
var txtBox = "";
var txtstatus = false;
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var val=$("#hidden_id").val();
var to = 'ch';
if (!t.is(':checked')){
var swap = to;
to = from;
from = swap;
} else {
txtstatus = true;
}
$(':checkbox:checked').attr('disabled', true);
$('#'+to).append(t.attr('name', to).parent());
$('#ch').addClass('br');
});
if(txtstatus){
txtBox = "<input type='text' value=''>";
$('#ch').after(txtBox);
}
});
//close buttom code
$('#cls').click( function() {
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var to = 'ch';
if (t.is(':checked')){
var swap = to;
to = from;
from = swap;
}
$(':checkbox:checked').attr('disabled', false);
$(':checkbox:checked').attr('checked', false);
$('#'+from).append(t.attr('name', from).parent());
});
});
Not the prettiest thing I have ever written. If you want to leave the empty ul's, just comment out the removeEmpties call. I didn't worry about checkbox order, but it would be easy to implement in a separate function after the checkbox is moved. I also assumed you wouldn't want them to move backward beyond the initial ul. If you want that functionality, you could just add another else if to the move function.
http://jsfiddle.net/pJgyu/13225/

Categories