What is the difference between these two blocks of JavaScript code? - javascript

Here's the code:
<form action="">
<input type="text" id="new_task" placeholder="Write New Task" required>
<input type="button" value="Add Task" id="add_task">
</form>
<div id="task_list">
</div>
Code 1:
document.getElementById("add_task").addEventListener("click",function(){
let new_task = document.getElementById("new_task").value;
document.getElementById("task_list").append(document.createElement("p").textContent=new_task);
});
Code 2:
document.getElementById("add_task").addEventListener("click",function(){
let new_task = document.getElementById("new_task").value;
let task_div = document.getElementById("task_list");
let task_p = document.createElement("p");
task_p.textContent = new_task;
task_div.append(task_p);
});
What is the difference between the two blocks of code?
I am trying to make a todo list website.
The first piece of code was appending the value from input inside the div but not creating p tag.
The second piece of code worked perfectly.
I want to know the difference.

The significant difference is this section of code block 1:
.append(document.createElement("p").textContent=new_task)
This does in fact create a <p> tag but it is not appended to the document yet. When you set the text content on this new <p> tag, that expression evaluates to the string new_task, so it's the same as saying
.append(new_task)
which is definitely not what you want.
The full expanded version of what code block 1 is essentially doing is:
document.getElementById("add_task").addEventListener("click",function(){
let new_task = document.getElementById("new_task").value;
let task_div = document.getElementById("task_list");
let task_p = document.createElement("p");
task_p.textContent = new_task;
task_div.append(new_task);
// different from:
// task_div.append(task_p)
});

Related

new line for title JavaScript

I'm trying to put every new word for title on the new line using js. I tried different ways, but they don't work.
dictionary.title += word.value; - here I add attribute title for my dictionary class with word.value value. It comes together like: "HelloI'mJohn" instead of
"Hello
I'm
John". How can I do that on the new line using JavaScript code?
Use
\n
or
br tag
for new line.
dictionary.title += word.value + "\n";
Like in the above answers as said you can use <br> and \n for the new line but there are many alternative ways you can achieve this for your understand I have written a code where I used a tag which is also called a block element where it takes given width and height and add a new line at the end automatically. There are many block-level elements you can also use for new lines.
let value = document.querySelector(".newInput");
let btn = document.querySelector("button");
let div = document.querySelector(".dictionary");
function storeValues(){
let dictionary = "";
if(value.value){
dictionary += `<p>${value.value}</p>`
}
div.innerHTML += dictionary
}
btn.addEventListener("click", storeValues);
Enter Word: <input type='text' class='newInput'/>
<button type='submit' class='newInput'>Submit</button>
<div class='dictionary'>
<!-- Dicitonary will appear here-->
</div>

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

add text to div with javascript

Hello I'm just starting to learn and I'm trying to write simple code to add text to a div box using java script but it gives me error query selector not defined
html code:
<h2>List of items</h2>
<input class="text" type="text" placeholder="write text"><br>
<input type="button" value="Add" onclick="addItem()">
<div class="list"></div>
java script code:
function addItem(){
let getText = querySelector("text").value;
let newText = document.createElement("div");
newText.innerHTML = document.appendChild("getText");
document.querySelector("list").appendChild("newText");
}
There are several issues in your code:
querySelector is a method of document object. It should be document.querySelector("selector").
document.appendChild expects a Node instance. You are passing a string.
You are missing . for the class selectors.
You should not wrap variables with "" when you are referring to them.
Here is the updated code:
function addItem() {
let getText = document.querySelector("input.text").value;
let newText = document.createElement("div");
newText.innerHTML = getText;
document.querySelector(".list").appendChild(newText);
}
use
document.querySelector("div.list").appendChild("newText");
instead of
document.querySelector("list").appendChild("newText");

Code made elements don't show on onload?

I've been tasked with a demo for a query API our company has. For that, my boss wanted me to create a simple HTML site containing a search feature to use said API. So far, I've managed to create almost everything she wanted, but am now stuck on a rather... Peculiar problem.
I've managed to create a flexible filtering feature, allowing the user to add/remove filters as they see fit. I've done it like this:
window.onload = function init()
{
var filterSet = document.getElementsByTagName("fieldset")[0];
var filterSection = filterSet.getElementsByTagName("section");
var set = filterSection[1];
var elements = set.getElementsByTagName("*");
set.getElementsByTagName("*")[5].addEventListener("click", cloneSection);
if (filterSection.length > 2)
{
elements[6].hidden = false;
elements[6].addEventListener("click", deleteSection);
}
else
{
elements[6].hidden = true;
}
}
function cloneSection(e)
{
var filterSet = document.getElementsByTagName("fieldset")[0];
var filterSection = filterSet.getElementsByTagName("section");
var newId = parseInt(filterSection[filterSection.length - 1].id) + 1;
var set = filterSection[1];
var newSet = set.cloneNode(true);
var elements = newSet.getElementsByTagName("*");
newSet.id = "" + newId;
elements[5].addEventListener("click", cloneSection);
elements[6].hidden = false;
elements[6].addEventListener("click", deleteSection);
filterSet.appendChild(newSet);
}
function deleteSection(e)
{
var target = e.target;
var filterSet = document.getElementsByTagName("fieldset")[1];
var filterSection = target.parentElement;
filterSection.remove();
}
<fieldset>
<section>
<input type="checkbox" id="filter_query" name="feature" value="search" />
</section>
<section id="0">
<input type="text" name="filter_name">
<select id="comperason_type">
<option value="=">Equal to</option>
<option value="!=">Different then</option>
</select>
<input type="text" name="filter_value">
<input type="submit" value="+" id="AddButton">
<input type="submit" value="-" id="RemoveButton" hidden="true">
</section>
</fieldset>
It's rather basic (I'm kinda new to networking and Javascript as a whole, I'll admit), but for the most part it works just fine. Except for one single issue.
I want, when the user adds a new filter, to allow them to remove the default one created by the original markup. The button is there, I just need to set it to hidden = false and that's it. Except... When I try to do that, for some reason, the code doesn't recognize the extra section created into it. For example, if there are 3 sections in the fieldset, one created by my own code, the length count will only return 2.
Does anyone know why? Or what can I do to get it to count properly? I'm sorry if this is a newb question, but like I said, I'm a bit out of my depth here.
EDIT: Made a snippet that works this time. Sorry for making it confusing, but it should be good now.

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources