Using a value from html with the name="example" - javascript

I created a page with a form, where you can enter a name.
When you submit the name, the name is stored under the name "bezeichnung".
Now i want to use the the input "bezeichnung" as a button label. And append it to the body of the page.
This is the form:
<head>
<link rel="stylesheet" href="\User\stl.css"/>
</head>
<body>
<h1> Neue Station hinzufügen</h1>
<form id="stationenformular" name="stationenformular" action="indexAktualisierung.html" method="get">
<div>
<label for="bezeichnung">Bezeichung der neuen Station:</label>
<input type="text" id="bezeichnung" name="bezeichung" />
</div>
<br><br>
<div>
<label for="ipadresse"> IP Adresse des Raspberry Pi:</label>
<input type="text" id="ipadresse" name="ipadresse"/text>
</div>
<div>
<br>
<input type="submit" value="Abschicken"/>
</div>
</form>
</body>
</head>
and this the function in another html script:
var x = document.getElementsByName("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);

For first your name is bezeichung, not bezeichnung.
Also getElementsByName returns an array-like object. You need to get the first item from your elements;
var x = document.getElementsByName("bezeichnung")[0]; // Get the first
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x.value); // Create a text node with x's value
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
See example. I added text by default.
var x = document.getElementsByName("bezeichnung")[0];
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x.value); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
<body>
<h1> Neue Station hinzufügen</h1>
<form id="stationenformular" name="stationenformular" action="indexAktualisierung.html" method="get">
<div>
<label for="bezeichnung">Bezeichung der neuen Station:</label>
<input type="text" id="bezeichnung" name="bezeichnung" value="Test"/>
</div>
<br><br>
<div>
<label for="ipadresse"> IP Adresse des Raspberry Pi:</label>
<input type="text" id="ipadresse" name="ipadresse"/text>
</div>
<div>
<br>
<input type="submit" value="Abschicken"/>
</div>
</form>
</body>

To get a unique instance of the bezeichnung input field, you could use var x = document.getElementsByName("bezeichnung")[0]; or var x = document.getElementById("bezeichnung");
As Suren Srapyan said, getElementsByName returns an array of all elements with that name, so you need to specify which one you mean by putting the position in the array of the object you want.
However, as you presumably only want one instance of bezeichnung, it's easier to use getElementById.

var x = document.getElementsByName("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x); // Create a text node
btn.parentNode.insertBefore(t, btn); // Append the text to <button>
document.body.appendChild(btn);

Try to change getElementsByName with getElementById
var x = document.getElementById("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
btn.innerText = x.value; // Append the text to <button>
document.body.appendChild(btn);
Demo

Related

How to get the innerHTML of an input in Java script

I am making a TODO list. I have difficulties with setting the input text on my card. Everything I write in the input, I want to select and to put on the card.
I tried to select the innerHTML of an input when I type something in. I don't know how to select the typed input text. I would then create a new element with the text inside, and would append it to the card.
let btn = document.querySelector('.add');
let textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
// eventlistner by button clicked
btn.addEventListener('click', function() {
var txt = document.getElementsByClassName('input').innerHTML;
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<buton class="add" type="button"> + </buton>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
To get the value of the input use the value property, not innerHTML. Also note that you already have a reference to the input Element in the input variable, so you don't need to use getElementsByClassName() to retrieve it - not least of all because the syntax there is flawed.
Once you have the text you can use createElement() to add a new p element to the .todotext container:
const btn = document.querySelector('.add');
const textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
btn.addEventListener('click', function() {
const txt = input.value;
if (!txt)
return;
const p = document.createElement('p');
p.textContent = txt;
textspace.appendChild(p);
input.value = '';
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<button class="add" type="button"> + </button>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
As others already answered your question. I just wanted to point out that there is a misspelling in your code (buton instead of button). Fix that and the button element would be rendered correctly.
First, getElementsByClassName will return HTMLCollection which is array-like, you need to use querySelector instead, also the innerHTML, textContent, innerText properties all are empty string for the input because the input is a self-closing tag without content inside, you need to use value property.
let btn = document.querySelector('.add');
let textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
// eventlistner by button clicked
btn.addEventListener('click', function() {
var txt = input.value;
console.log(txt)
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<buton class="add" type="button"> + </buton>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
btn.addEventListener('click', function() {
var txt = document.getElementByClassName('input').value;
});
You were using getElementByClassName which will be HTMLCollection.To loop over each element you need to convert it into an array loop over them.
var txt = document.getElementsByClassName('input').value;
You should get the value of an input , not the innerHTML
Also assign a unique id to you input fields and select them with it, it's much better :)

Div not being created n amount of times from for loop (javascript)

so I'm trying to create a div as many times as is entered in an input field (in the div "controls left" with the name "quantity).
I've created a for loop to append the child divs to the parent div but nothing is happening?
this is the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="task3.js"></script>
<link rel="stylesheet" type="text/css" href="task3.css" />
<meta charset="UTF-8">
<title>Practical Excercise 3 - Part 3</title>
</head>
<body>
<div id="main" class="container">
<button class="right" onclick="menuClick()">MENU</button>
<h1>Part 3 - Javascript Playground</h1>
<div id="mcount" onmouseover="mousePassCtr()"></div>
<div id="posts">
</div>
<hr />
<textarea id="text-content" rows="4" cols="60">Type your text here...</textarea>
<br />
<div class="controls left">
<input type="number" name="quantity" value="1" /><br />
<input id="blue" type="radio" name="color" value="blue" /> Blue<br />
<input id="red" type="radio" name="color" value="red" /> Red<br />
<button onclick="postClick()">Post</button>
</div>
<div class="controls left">
<input type="range" name="visible" min="1" max="10" value="10"/><br />
<input type="checkbox" name="style" value="bold" /> Bold<br />
<input type="checkbox" name="style" value="italic" /> Italic<br />
<select>
<option disabled selected value="-1">Choose a post to reply to</option>
</select>
</div>
<hr />
</div>
<div id="menu" class="container" style="display:none;">
<button class="right" onclick="backClick()">BACK</button>
<p> </p>
<span>Background Color:</span><input type="text">
</div>
</body>
</html>
this is the js
function postClick() {
var mainPostDiv = document.getElementById("posts"); // Creating variable for the main post div
// Creating a date paragraph within the HTML doc and appending it with the date of the post
var dateDiv = document.createElement('P'); // creating the date div
dateDiv.setAttribute("class", "post-time"); // setting the class of the div
var date = new Date(); // initializing time of posts date to date variable
var dateLocale = date.toLocaleString(); // converting the date to a locale version and to a string
var dateTimeNode = document.createTextNode(dateLocale); // creating a node on DOM tree with the locale date in it
dateDiv.style.fontWeight = "bold"; // changing the dates font-weight to bold
dateDiv.style.color ="grey"; // changing the dates font-color to grey
dateDiv.appendChild(dateTimeNode); // appending the date node to the date div
// Creating a content paragraph and appending it with the content within the input field
var contentDiv = document.createElement('P'); // creating the content div
contentDiv.setAttribute("class", "post-content"); // setting the class of the div
var content = document.getElementById("text-content").value; // getting the value inside of the input field and assigning it to content
var contentNode = document.createTextNode(content); // creating a node containing the content value
contentDiv.appendChild(contentNode); // apending the content node to the content div
var postNum = document.getElementsByName("quantity").value;
var blueChecker = document.getElementById("blue");
var redChecker = document.getElementById("red");
for (var i = 0; i < postNum; i++) {
mainPostDiv.appendChild(dateDiv);
mainPostDiv.appendChild(contentDiv);
}
}
any help is appreciated, thanks
You need to select the first element from document.getElementsByName("quantity"), as it returns an array of elements. Change it to var postNum = document.getElementsByName("quantity")[0].value; so that you can have the value of the first element
Try to write this
var postNum = document.getElementsByName("quantity").value;
Like that
var postNum = document.querySelector("input[name='quantity']").value;
Because getElementsByName() method of the Document object returns a collection of NodeList elements with the given name
Move the code for creating dateDiv and contentDiv into a for loop like this
var mainPostDiv = document.getElementById("posts"); // Creating variable for the main post div
var postNum = document.querySelector("input[name='quantity']").value;
var blueChecker = document.getElementById("blue");
var redChecker = document.getElementById("red");
for (var i = 0; i < postNum; i++) {
// Creating a date paragraph within the HTML doc and appending it with the date of the post
var dateDiv = document.createElement('P'); // creating the date div
dateDiv.setAttribute("class", "post-time"); // setting the class of the div
var date = new Date(); // initializing time of posts date to date variable
var dateLocale = date.toLocaleString(); // converting the date to a locale version and to a string
var dateTimeNode = document.createTextNode(dateLocale); // creating a node on DOM tree with the locale date in it
dateDiv.style.fontWeight = "bold"; // changing the dates font-weight to bold
dateDiv.style.color = "grey"; // changing the dates font-color to grey
dateDiv.appendChild(dateTimeNode); // appending the date node to the date div
// Creating a content paragraph and appending it with the content within the input field
var contentDiv = document.createElement('P'); // creating the content div
contentDiv.setAttribute("class", "post-content"); // setting the class of the div
var content = document.getElementById("text-content").value; // getting the value inside of the input field and assigning it to content
var contentNode = document.createTextNode(content); // creating a node containing the content value
contentDiv.appendChild(contentNode); // apending the content node to the content div
mainPostDiv.appendChild(dateDiv);
mainPostDiv.appendChild(contentDiv);
}

More suitable method to remove 'li' Elements from List?

This solution below works for adding and removing list items. I had to implement Math.random() in order to set a unique id for each element. I was thinking in the professional world this definitely wouldn't cut it considering the chance of a repeating ID.
Wanted to know what would be a more suitable implementation? Any feedback welcome!
Thanks!
HTML
<html>
<head>
<body>
<p id = 'listTitle'> Your List </p>
<form onsubmit = "return false">
<input id = 'inputBar' type = "text" placeholder = "Enter Item"></input>
<input type = "submit" onclick = "getName()"></input>
<input type = "button" value = "Remove" </input>
</form>
<ol id = 'demo'>
</ol>
</body>
</head>
</html>
JS
function getName() {
var input = document.getElementById('inputBar').value
var list = document.getElementById('demo')
var entry = document.createElement('li')
entry.setAttribute("id", Math.floor(Math.random()* (100 - 1) + 1 ))
console.log(entry.id)
entry.setAttribute("onclick", "removeName(this.id)")
entry.appendChild(document.createTextNode(input))
list.appendChild(entry)
}
function removeName(removeID) {
var listItem = document.getElementById(removeID)
listItem.remove()
}
There's no need for dynamic IDs. When appending the new element, just attach a listener that calls entry.remove() when clicked. You can also assign to the textContent instead of using the unnecessarily verbose createTextNode / appendChild.
function getName() {
const inputValue = document.getElementById('inputBar').value;
const li = document.getElementById('demo').appendChild(document.createElement('li'));
li.onclick = () => li.remove();
li.textContent = inputValue;
}
<p id='listTitle'> Your List </p>
<form onsubmit="return false">
<input id='inputBar' type="text" placeholder="Enter Item"></input>
<input type="submit" onclick="getName()"></input>
<input type="button" value="Remove" </input>
</form>
<ol id='demo'>
</ol>

How to remove previously created element before adding new set of elements

<html>
<body>
<input type="text" id="number"/>
<input type="button" value="create button" onclick="createbtn()"/>
<br>
<script>
function createbtn()
{
var n=document.getElementById("number").value;
for(i=1;i<=n;i++)
{
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", i);
x.setAttribute("id","x"+i);
document.body.appendChild(x);
}
}
</script>
</body>
</html>
The above code takes the value from text field and creates number of buttons equal to the value entered in text field.Now if new value is entered in text I wanted to clear previously created button before creating new buttons.How can this be achieved?
Just create an element, i.e. a div and clear it before adding new elements. Something like:
<html>
<body>
<div id="result"></div>
<input type="text" id="number"/>
<input type="button" value="create button" onclick="createbtn()"/>
<br>
<script>
function createbtn(){
var n=document.getElementById("number").value;
document.getElementById("result").innerHTML = "";
for(i=1;i<=n;i++){
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", i);
x.setAttribute("id","x"+i);
document.getElementById("result").appendChild(x);
}
}
</script>
JSFIDDLE
Assign a class name to the newly-creating elements.
x.setAttribute("class", "some-class-name");
Then remove all elements byClass, before adding the new ones.
Add a button container element and add all buttons to that container. Clear the contents before you add new ones.
Create a container in which to put the buttons. At the start of your function, clear the container.
<input type="text" id="number"/>
<input type="button" value="create button" onclick="createbtn()"/>
<div class="buttons"></div>
<script>
function createbtn()
{
var buttons_container = document.getElementsByClassName("buttons")[0];
var n=document.getElementById("number").value;
buttons_container.innerHTML = '';
for(i=1;i<=n;i++)
{
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", i);
x.setAttribute("id","x"+i);
buttons_container.appendChild(x);
}
}
</script>
https://jsfiddle.net/c3j1ebre/

JavaScript Appended Element Text Not Showing

I'm trying to create an online to do list for users and I want it to function so that when you enter a task and click the 'JotIT' button the task is appended.
So far the function to append works but the text is not visible for some reason even though when I inspect it, the text shows up in the HTML.
<script>
var welcome = 'Welcome To JotIT';
var jotItem = function()
{
//Create & Get the necessary elements
var item = document.createElement('input'),
space = document.createElement('br'),
form = document.getElementById("listing"),
frag = document.createDocumentFragment(),
textVal = document.getElementById("input-jot");
//Set Attributes to list item
item.setAttribute('type', 'checkbox');
item.setAttribute('name', 'jot-list');
//If there is no input in the textbox then create an alert popup
if(textVal.value === "")
alert("Please insert a value");
else {
item.innerHTML = textVal.value;
frag.appendChild(item);
frag.appendChild(space);
form.appendChild(frag);
textVal.value = "";
}
}
</script>
</head>
<body>
<h1 id="head">JotIT</h1><br>
<p> <script type="text/javascript">document.write(welcome);</script></p>
<input type="form" id= "input-jot">
<button class = 'btn-info' id="jot-down" onclick=jotItem();>JotIt!</button>
<!-- TODO: Add form submit tag instead of ul tag -->
<!-- TODO: Align the list items -->
<form id = "listing" method="get">
<input type="checkbox" name="me"> Start </input>
</form>
</body>
You Have to insert a label. Inputs should be self closing / empty elements. In particular an input of type checkbox won't correctly display a label. Use the label element for this purpose instead.
var welcome = 'Welcome To JotIT';
var jotItem = function() {
//Create & Get the necessary elements
var item = document.createElement('input'),
label = document.createElement('label'),
space = document.createElement('br'),
form = document.getElementById("listing"),
frag = document.createDocumentFragment(),
textVal = document.getElementById("input-jot");
//Set Attributes to list item
item.setAttribute('type', 'checkbox');
item.setAttribute('name', 'jot-list');
//If there is no input in the textbox then create an alert popup
if (textVal.value === "")
alert("Please insert a value");
else {
label.innerText = textVal.value;
frag.appendChild(label); // here goes the label
frag.appendChild(item);
frag.appendChild(space);
form.appendChild(frag);
textVal.value = "";
}
}
</head>
<body>
<h1 id="head">JotIT</h1>
<br>
<input type="form" id="input-jot">
<button class='btn-info' id="jot-down" onclick=jotItem();>JotIt!</button>
<!-- TODO: Add form submit tag instead of ul tag -->
<!-- TODO: Align the list items -->
<form id="listing" method="get">
<label>Start</label>
<input type="checkbox" name="me" />
</form>
</body>
This has to do with the fact that you're adding the label to the input incorrectly. Use the below HTML syntax and it will resolve your issue:
<label><input type="checkbox" name="jot-list" />The Text</label>

Categories