Javascript - How to add <input> element into div using createElement Method - javascript

I have a problem with simple thing.
I want to add a element into html div tag using createElement Method. I have tried a lot of diferent ways but always getting the same result - nothing happens.
This is my code:
function changeReleaseDate()
{
var parentElement = document.getElementByClassName("container body-content");
var existingElement = document.getElementByClassName("btn btn-default");
var newInput = document.createElement("input");
newInput.type = "text";
newInput.className = "form-control";
parentElement.insertBefore(newInput, existingElement);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="container body-content">
<h2>Index</h2>
<button id="btn" type="button" onclick="changeReleaseDate()" class="btn btn-default">Default</button>
<hr />
<footer>
<p>©My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
I also tried to use appendChild but in this case input field was placed out of div.

The problem is that getElementByClassName should be getElementsByClassName.
This method returns a HTMLCollection, so to access the first element from this list you need to use bracket with index 0:
var parentElement = document.getElementsByClassName("container body-content")[0];
var existingElement = document.getElementsByClassName("btn btn-default")[0];
Demo: http://jsfiddle.net/jak4efau/
However it's more convenient in your case to use querySelector method:
var parentElement = document.querySelector(".container body-content");
var existingElement = document.querySelector(".btn.btn-default");
Also note, that you need to take care of the case when user clicks button multiple times, you probably don't want to append multiple input fields.

Related

How to print each array element on a new row

I am getting a new array element from an input and adding to array but I can not print every element in a new row. I can print all elements of array in one row but can not print every element in a different row. I am using <br> after array name but does not work. What is your solution? It is like a todo list project.
var allmembers = [""];
function addnewmember() {
var newmemberr = document.getElementById("newmember").value;
allmembers.push(newmemberr);
for (var i = 0; i < allmembers.length; i++) {
document.getElementById("membername").innerHTML = allmembers[i] + "<br>";
}
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>
Your solution is appending a <br> to the end of the array, rather than between array items. Instead of looping over the array, just use the .join() method, which is ideal for something like this.
Additionally, using innerHTML in a loop is a big performance "no no" as it causes the browser to have to repaint and possibly reflow the DOM document repeatedly. In such cases, you should build up a string that contains the HTML you want and after the loop is done set that string as the innerHTML of the desired element in one single command. And really, the use of innerHTML should be avoided if at all possible because of security concerns as well.
See additional comments inline:
let allmembers = [];
// Get your DOM references just once, not every time the function runs
// Make references to DOM elements, rather than their propreties. This
// way, if you decide you need access to a different DOM element property
// you don't have to scan for the element again.
let newmember = document.getElementById("newmember");
let memberName = document.getElementById("membername");
function addnewmember() {
allmembers.push(newmember.value);
newmember.value = ""; // Clear out the input
// No need for a loop. Just join the arry elements
// with a <br> between them.
memberName.innerHTML = allmembers.join("<br>");
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>

Why is my .parentNode returning undefined? [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I´m trying to make a simple To-do List, and I want it to have a button to add the tasks that I want and another button to remove all tasks but when I click the delete button I get an error: "Cannot read property 'removeChild' of undefined" I don´t know why it says the parentNode is undefined.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>To do List</title>
</head>
<body>
<header>
<h1>To-do List</h1>
<div id="form">
<input type="text" name="" id="tarefa" value="Add an item!">
<button id="submit">Submit</button>
<button id="delete">Clear List</button>
</div>
</header>
<main>
<ul id="lista">
<li id="112">Test1</li>
<li>Test2</li>
</ul>
</main>
<script src="javascript.js"></script>
</body>
</html>
//Javascript file
const tarefa = document.getElementById("tarefa")
const adicionar = document.getElementById("submit")
const limpar = document.getElementById("delete")
const padre = document.getElementById("lista")
const fpp = document.querySelectorAll("li")
//Add the tasks
function enviar(e){
var coisa = document.createElement("li")
let escrito = tarefa.value;
padre.appendChild(coisa)
coisa.innerHTML = escrito
}
//Delete the tasks
function apagar(e){
fpp.parentNode.removeChild(fpp)
console.log("aaaa")
}
adicionar.addEventListener("click",enviar)
limpar.addEventListener("click",apagar)
.querySelectorAll returns a NodeList (because you're selecting all li tags, not just one), so you need to do a forEach loop. Give the context, I asume fds is supposed to be fpp (you never define fds in the code you provided), so here is the code you would need, given that assumption:
function apagar(e){
fpp.forEach(function(el) {
el.parentNode.removeChild(el)
})
}
Update
Use this so that you dont get null errors once the list is deleted the first time.
function apagar(e){
document.querySelectorAll("li").forEach(function(el) {
el.parentNode.removeChild(el)
})
}
How about
function apagar(){
padre.innerHTML = "";
}

After a button is clicked/form submit, the CSS stylesheet doesn't appear

After the use button is clicked, the sources when I inspect the page show that the style.css page goes away, and no styles are applied. I can't figure out why this is happening.
My index.html page looks like this:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;500&family=Roboto:wght#100;300;400;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="First name" class="fname">
<input type="submit" value="Use" class="submit">
<script src="app.js"></script>
</body>
</html>
And my app.js is this:
const useBtn = document.querySelector('.submit');
const reloadBtn = document.querySelector('.btn__reload')
document.body.style.fontFamily = "Roboto;"
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
document.write(`<h2>It's ${person}'s turn!</h2>`)
document.write(`<h4>How long will they live?</h4>`)
let oldAge = `<p>${Math.floor((Math.random() * 10)+ 30)}</p>`
document.write(oldAge)
document.write(`<h4>What will be their yearly salary?</h4>`)
let salary = `<p>${Math.floor(Math.random() * 10000)}</p>`
document.write(salary)
document.write(`<h4>What will be their career</h4>`)
const jobs = [ 'plumber', 'doctor', 'witch', 'president', 'trump supporter']
let job = Math.floor(Math.random() * jobs.length)
document.write(jobs[job])
redoBtn();
})
function redoBtn(){
let tryAgain = document.createElement('button')
document.body.appendChild(tryAgain)
let buttonText = document.createTextNode('Try Again')
tryAgain.appendChild(buttonText)
tryAgain.addEventListener('click', function(){
window.location.href = window.location.href;
})
}
Any help is so appreciated!
Your document.write is overwriting all your html, including your linked stylesheet.
From https://developer.mozilla.org/en-US/docs/Web/API/Document/write:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
If you really want to use document.write, you'll need to rewrite your stylesheet link into the new document. But it might be better to just replace the html of some container element on your page, like the body element.
Instead of using document.write which overwrites your html you could try this approach:
<input type="submit" value="Use" class="submit">
<!-- add new div to show the result -->
<div id="result"></div>
<script src="app.js"></script>
And in the click event:
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
let res = document.getElementById('result');
res.innerHTML = "<h2>It's "+person+"'s turn!</h2>";
// add further information to innerHTML here
// hide input fname and submit button
redoBtn();
})

I can't figure out how to append a user's input into an array in Javascript

I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>

Beginner javascript arrays

I am new to JavaScript and I am trying to do something very simple. I wan to appear array[1] text in firstDiv's innerHTML when I click button.
I have followed all instructions but still it's not working.
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta htttp-equiv="content-type" contents="text/html; charset-utf8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<button id="stylesChanger">Change the text !</button>
<div id="firstDiv">This sis some text</div>
<script type="text/javascript">
var myArray=new Array[];
myArray[0]="pizza";
myArray[1]="chocolate";
document.getElementById("stylesChanger").onclick=function(){
document.getElementById("firstDiv").innerHTML=myArray[1];
}
</script
</body>
</html>
change your var myArray=new Array[]; to var myArray=[];
Then it will work
var myArray=[];
myArray[0]="pizza";
myArray[1]="chocolate";
document.getElementById("stylesChanger").onclick=function(){
document.getElementById("firstDiv").innerHTML=myArray[1];
}
<button id="stylesChanger">Change the text !</button>
<div id="firstDiv">This sis some text</div>
This code will make sure you get the first element of myArray on button click. And sets the div text as myArray first element.
Working Sample: JSFIDDLE
var myArray = new Array();
myArray[0] = 'pizza';
myArray[1] = 'chocolate';
var btn = document.getElementById('stylesChanger');
btn.addEventListener('click', getArrayFirstElement, false);
function getArrayFirstElement(){
document.getElementById("firstDiv").innerHTML = myArray[0];
}

Categories