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++;`
Related
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
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
The code below gets info from xml file.
I succesfully presents the id and name of each planet with a button.
I want to add an onclick event on the button.
Problem now is: it does add the onclick event but only on the last button created in the loop.
What am i doing wrong? Why doesnt it create a onclick event for each button, but only for the last one in loop?
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
valDiv = ''; // clear valDiv each time loop starts
// Get the id and the name from the xml info in current <planet> tag
valDiv += planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
valDiv += planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (i + 1);
valButton.object = this;
//
// Here is the problem i cant get fixed
//
//valButton.onclick = function(){ showinfo(); }
valButton.addEventListener('click', showinfo);
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}
}
// simple function to check if it works
function showinfo() {
console.log(this.object);
console.log(this.id);
}
The trouble is this line:
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
When you set innerHTML the content currently in there gets destroyed and replaced with the new html, meaning all your old buttons are now destroyed and new ones are created. The previously attached event listeners do not get attached to the new buttons.
Instead simply create a div/span or whatever container would best help, add your planet text or whatever to it and then use appendChild
valDiv = document.createElement("div");
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
You could also use insertAdjacentHTML
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv = id+"<br>"+name+"<br>";
document.getElementById("planetenID").insertAdjacentHTML("beforeend",valDiv);
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
(function(num){
valDiv = document.createElement("div");
// Get the id and the name from the xml info in current <planet> tag
var id = planets[num].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
var name = planets[num].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (num + 1);
valButton.object = this;
// FIX: PASS showinfo TO AN ANONYMOUS FUNCTION CONTAINING THE OBJECT
valButton.addEventListener('click', function(){
showinfo(valButton);
});
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}(i));
}
}
// simple function to check if it works
function showinfo(valButton) {
console.log(valButton.object);
console.log(valButton.id);
}
I am attempting to remove an entire element and recreate it on an event:
I cannot seem to get this right despite several variations of the same code:
For example on event, I need to remove the element and then recreate the same element. I do not want to remove the text:
This is what I have tried (experimental): The result is inconsistent and the code is repetitive.
function removeCreate(){
var input = document.getElementById('display');
var body = document.getElementsByTagName('body')[0];
if(!!input){
input.parentNode.removeChild(input);
input = document.createElement('input');
input.id = 'display';
input.setAttribute('type',"text");
body.appendChild(input);
} else {
input.parentNode.removeChild(input);
input = document.createElement('input');
input.id = 'display';
input.setAttribute('type',"text");
body.appendChild(input);
}
}
Your reason for removing your input element and re-creating it is quite unclear, but let's say it gets modified somehow and you want to "reset" its state.
When you say "I do not want to remove the text", the most probable thing I understand is that you want to keep the current value that the user has typed into your input.
If this fits your situation, then you could simply hold a "template" of your input element in memory, so that you can clone it when needed and use the clone to replace the one in DOM. When doing so, retrieve first the current input value, and inject it back into the cloned input.
Result:
var inputTemplate = document.createElement('input');
inputTemplate.setAttribute('type', 'text');
function cloneInput() {
var newInput = inputTemplate.cloneNode(true);
newInput.id = 'display';
return newInput;
}
var input = document.getElementById('display');
var body = document.getElementsByTagName('body')[0];
if(!!input){
// First retrieve the current value (what the user has typed / default value)
var value = input.value;
input.parentNode.removeChild(input);
input = cloneInput();
input.value = value; // Re-inject the value.
body.appendChild(input); // Note that this would put your input at the bottom of the page.
} else {
//input.parentNode.removeChild(input); // useless?
input = cloneInput();
body.appendChild(input);
}
I am trying to make a combobox in javascript and populate it from an array. On selection I want to change a variable, call a function etc. I have looked at multiple tutorials on-line but for such an easy task the tutorials are dire.
Can anyone help?
Cheers
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theOptions = ['option 1','option 2','option 3'];
// Create the container <div>
theContainer = document.createElement('div');
theContainer.id = 'my_new_div';
// Create the <select>
theSelect = document.createElement('select');
// Give the <select> some attributes
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.className = 'class_of_select';
// Define something to do onChange
theSelect.onchange = function () {
// Do whatever you want to do when the select changes
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = theOptions.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = i;
anOption.innerHTML = theOptions[i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);