JavaScript Appended Element Text Not Showing - javascript

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>

Related

How to Remove Input text after submit HTML JavaScript

I have a dialog that contains inputs,
User should complete dialog inputs then click send,
After that, user can open the same dialog again and complete dialog inputs.
But when the user open the dialog again, input values remain as same from previous inputs,
How can I remove previous input values?
My Dialog:
<dialog id="main-customers">
<h2>العملاء الرئيسيون</h2>
<div>
<label for="main-customers-name">الاسم</label>
<input type="text" id="main-customers-name" placeholder="الاسم" required>
<label for="main-customers-country">الدولة</label>
<input type="text" id="main-customers-country" placeholder="الدولة" required>
<label for="main-customers-goods">سلع / بضائع</label>
<input type="text" id="main-customers-goods" placeholder="سلع / بضائع" required>
</div>
<div class="center">
<button id="main-customers-send">إرسال</button>
<button id="main-customers-cancel" onclick="closeDialog('main-customers')">إلغاء</button>
</div>
</dialog>
My JS:
document.getElementById("main-customers-send").addEventListener("click", function(){
// to remove initial value
var no_data= document.getElementById("main-customers-table-no-data");
if(no_data){
no_data.remove()
}
// END to remove initial value
var name= document.getElementById("main-customers-name");
var country= document.getElementById("main-customers-country");
var goods= document.getElementById("main-customers-goods");
document.getElementById("main-customers-table").innerHTML+=
`<tr>
<td>${name.value}</td>
<td>${country.value}</td>
<td>${goods.value}</td>
</tr>`;
let itms = document.querySelectorAll("#main-customers");
for (let itm of itms) {
if(itm.value != ""){
itm.value= ""; //it does not do the job
}
}
closeDialog("main-customers")
})
-
values remain the same as shown below:
The line let itms = document.querySelectorAll("#main-customers"); doesn't do what you think it does. It selects all the elements with the id "main-customers" (which per spec a page could only have one of).
Try let itms = document.querySelectorAll("#main-customers input[type=text]"); instead of that which will select all the children of the #main-customers element that is an input whose type is text.

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);
}

Removing Checked checkbox elements using a function

Trying to make a to-do list using JavaScript but can't seem to figure out a way to delete the checked checkboxes.
I tried to have the program change the id then delete everything with that new id but that didn't seem to work, maybe I was missing something important not sure but if any of you know a different way of deleting checked checkboxes, I'd appreciate the help.
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
} else {
document.getElementById("myUL").appendChild(checkbox);
}
// Assigning the attributes to created checkbox
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "checkBox";
// create label for checkbox
var label = document.createElement('label');
// assigning attributes for the created label tag
label.htmlFor = "checkBox";
// appending the created text to the created label tag
label.appendChild(document.createTextNode(inputValue));
// appending the checkbox and label to div
myDiv.appendChild(checkbox);
myDiv.appendChild(label);
}
function remove() {
var doc = document.getElementById("checkBox").checked;
doc.remove;
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
There are several issues to your code:
You are recycling the #checkBox ID. Remember that IDs must be unique within a document. Therefore, you should be generating a unique ID for each label + checkbox pair
You are only removing the checkbox element and not the label text, so even if your logic works, the appearance / outcome of your code is not what you want.
A solution will be wrapping your label text and the checkbox element inside the label. The advantages of this is that:
The <label> element does not need a for attribute, since clicking on the label will automatically check the nested checkbox
You can use .closest('label') to remove the entire label text + checkbox pair, when you hit the delete button
In order to iterate through all the checked checkboxes, you can simply run this selector: document.querySelector('.checkbox:checked'). To iterate through this Node collection, you can use Array.prototype.forEach().
Another note: you might want to return from the function if there an empty text is provided when a user wants to add a textbox.
See proof-of-concept example below:
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
return;
} else {
document.getElementById("myUL").appendChild(checkbox);
}
// Assigning the attributes to created checkbox
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.classList.add("checkbox");
// create label for checkbox
var label = document.createElement('label');
// appending the checkbox and created text to the created label tag
label.appendChild(checkbox);
label.appendChild(document.createTextNode(inputValue));
// appending label to div
myDiv.appendChild(label);
}
function remove() {
const checkboxes = document.querySelectorAll('.checkbox:checked');
Array.prototype.forEach.call(checkboxes, function(checkbox) {
checkbox.closest('label').remove();
});
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
I think you should restructure your html. Create a separate function createItem() which
returns a <div> containing <input> and text. Give a specific className to container div.
Inside remove() you querySelectorAll() to get all items. And use forEach() to loop through items and check if the input of item is checked then remove() it
Note: id of the element in whole document should be unique
function createItem(text){
const container = document.createElement('div');
container.className = 'item'
container.innerHTML = `<input type="checkbox" /><span>${text}</span>`
return container;
}
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
} else {
document.getElementById("myUL").appendChild(createItem(inputValue));
}
}
function remove() {
var doc = document.querySelectorAll('.item');
doc.forEach(x => {
if(x.querySelector('input').checked){
x.remove()
}
})
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
Use a query:
function removeCheckedCheckboxes() {
const query = document.querySelectorAll('[type="checkbox"]:checked');
Array.from(query).forEach(element =>
element.remove()
);
}
<html>
<body>
<span style="background: red; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: orange; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: yellow; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: green; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: blue; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: purple; display: inline-block">
<input type="checkbox">
</span>
<br>
<br>
<button onclick="removeCheckedCheckboxes()">
Remove checked checkboxes
</button>
</body>
</html>

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

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

Make hidden input field visible HTML Javascript

Html input field is inside anchor tag like so ..
<a id="brand" onclick="myFunction()" class="brand" ><input id="mytext" onclick="myFunction()" type="hidden" value="Anchor Title">Anchor Title</a>
Javascript uses set attribute
<script>
function myFunction() {
document.getElementById("brand").innerHTML = "";
document.getElementById("mytext").setAttribute("type", "text");
var elem = document.getElementById("mytext");
elem.value = "Edit Title";
document.getElementById("brand").innerHTML = elem.value;
}
</script>
ACTUAL RESULTS
Anchor title is cleared on click
But, the input field is still hidden
Wanting To Achieve
Anchor title cleared on click
Input text field appears
User inputs text
Text from input becomes anchor title
Input field becomes hidden again
I think you should remove the line:
document.getElementById("brand").innerHTML = "";
(I don't know but maybe you delete the input element by that.)
Notice that when you do document.getElementById("brand").innerHTML = ""; you are deleting all things there are between <a id="brand"> and </a>, in this case the <input> line.
My solution:
<html>
<script>
function myFunction1() {
var elem1 = document.getElementById("mytext1")
elem1.setAttribute("type", "text");
elem1.value="Edit Title";
document.getElementById("mytext2").innerHTML = "";
}
function myFunction2() {
var elem1 = document.getElementById("mytext1")
elem1.setAttribute("type", "hidden");
document.getElementById("mytext2").innerHTML = elem1.value;
}
</script>
<a id="brand" onclick="myFunction1()" class="brand" >
<input id="mytext1" onchange="myFunction2()" type="hidden" value="Anchor Title">
<span id="mytext2">Anchor Title</span>
</a>
</html>

Categories