How can I make multiple inputs every time I enter an input? - javascript

I am creating a google extension called manga extension. It all went well until I crossed with input. I like to put an input number every time I enter a manga name in the main input, naming it with chapter with input. But when I enter a new manga name, the value of every input I entered is lost. And I don't know how to put it inside of localStorage. How should I make it?
const divInput = []
const mangaName = document.getElementById('mangaNameInList')
// the manga name
const deleteBtn = document.getElementById('deleteBtn')
let mangaChapters = document.createElement('input')
let mangaLists = document.getElementById('mangaLists')
// the div i created in html
let count = 0
mangaName.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
count += 1
mangaLists.innerHTML += `<p> ${mangaName.value}
<em>chapter</em>
<input type="number" class="mangaChapters ${count}"
onkeyup="getValue(event)">
</p>`
// the input that i was conflicted with
}
})
function getValue(event) {
if (event.key == 'Enter') {
mangaChapters = document.getElementsByClassName(`mangaChapters`)
divInput.push(mangaChapters.value)
}
}
every time I entered the main input (mangaName) and displaying it in the innerHTML, I just concatenate it with and and that's the problem, how can I get the value of every declared input that I make in inside the mangaName?
<!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>Manga Extension</title>
</head>
<body>
<h1>Manga Name Lists</h1>
<input type="text" id="mangaNameInList">
<button id="deleteBtn">DELETE ALL</button>
<div id="mangaLists"></div>
<script src="script.js"></script>
</body>
</html>
here's the html code. thanks for taking time to answer my coding question :)))

Related

Why isnt my button displaying value onto the div

I want the button with the id of number1 to display the value of 1 on to the input box which has the id of quest which is short for question.I also want to know if my code can be made more readable.
<!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">
<title>Calucator</title>
<style>
body{
text-align: center;
}
</style>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
</head>
<body>
<h1>Calucator</h1>
<input type="number" placeholder="Enter now" name="" id="quest">
<button onclick="run()">=</button>
<br>
<button onclick="" id="number1">1</button>
</body>
</html>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
//PROBLEM 1: You are not attaching yourElement to the DOM. See Element.insertBefore / Element.appendChild
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
And
<button onclick="run()">=</button>
Problem 2: Don't use inline element event handling. It isn't safe and Content-Security-Policy won't allow it. Instead, use JavaScript Element.addEventListener(...)

Call a function on Input Completion

I have a name input on 1.html.
I need to call a function where the input will be stored after completion, and when the person clicks ~next~ to go to the next page (2.html), whatever was stored appears there.
Example:
~1.html~
What's your name?
~input~ John ~input~
~2.html~
Hi, John! How can i help you?
I know i can use Session Storage to do it, but i'm not sure on how to proceed.
Here's what i have:
1.html
<p>"Whats Your Name?"</p>
<input id="your-name-input" type="text">
<a href="2.html">
<button id="next-button">Next</button>
<script>
nextButton = document.getElementById("next-button);
nextButton.addEventListener("click", () => {
var name = document.getElementbyId("your-name-input").value;
if(name !== "") {
sessionStorage.setItem("name", name);
} else {
alert("Please fill yout name")
});
</script>
And then, on 2.html i have:
<p id="user-name"></p>
What i'm trying to do, is to put inside the <p>, the following greeting:
Hi (name.value), how can i help you?
How can i call a function that loads the name value on the 2.html page when the page loads?
The below code should work. There are a few things missing in your code, not sure if you copied everything in.
In either case, the below works for me. You just need to update the link in the window.location = syntax. When you do that, it will take your stored value to the new page in the same tab, and display it using the script code in 2.html.
Code in 1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>Your name test</title>
</head>
<body>
<p>Whats Your Name?</p>
<input id="your-name-input" type="text">
<button id="next-button">Next</button>
<script>
const nextButton = document.getElementById("next-button");
const input = document.getElementById("your-name-input");
nextButton.addEventListener("click", () => {
const name = input.value;
if(name !== "") {
sessionStorage.setItem("name", name);
window.location = "<link to your 2.html file>";
} else {
alert("Please fill your name")
}
});
</script>
</body>
<footer>
</footer>
</html>
Code in 2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>See, it works</title>
</head>
<body>
<p id="user-name"></p>
<script>
const displayText = document.getElementById("user-name");
const storedValue = sessionStorage.getItem("name");
console.log(storedValue);
window.addEventListener("load", () => {
displayText.innerHTML = "Hi " + storedValue;
})
</script>
</body>
<footer>
</footer>
</html>
Original ans to original question:
You could use an addEventListener with an IF statement for your 'next' button and then the code you already have for localStorage.
Depending on what you need from your page, you could also use sessionStorage - that one doesn't save the input forever so might save, albeit limited, space on your user's computer.
I don't see the HTML for your button yet. But assuming you have it, here's an option for the rest of your code in 1.html.
Inside 1.html script tag:
nextButton = document.getElementById("yourButtonID");
nextButton.addEventListener("click", () => {
var name = document.getElementById("your-name-input").value;
if(name !== "") { // if input is not empty
localStorage.setItem("name", name); // set the value in localStorage
} else {
alert("Please fill your name")} // else, display an alert (if you like)
});

Program not getting value of a text field in JavaScript [duplicate]

This question already has an answer here:
Why is the value of my input always empty if I store it in a variable?
(1 answer)
Closed last year.
I am not really sure what is happening but I want to write a program that puts commas in a number you input, but when I run it and input a number the output is blank. Can anyone help???
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
</head>
<body>
<h1>Enter your number below:</h1>
<input type="text" placeholder="Right here" id="number">
<button id="submitButton">Add commas</button><br>
<h1 id="numberWithCommas">0</h1>
</body>
</html>
JavaScript:
const number = document.querySelector("#number").value;
let answerElement = document.querySelector("#numberWithCommas")
const button = document.querySelector("#submitButton");
button.addEventListener("click", () => {
answerElement.textContent = number.toLocaleString();
})
I am not really sure what is happening so I can't tell you much. Sorry.
let answerElement = document.getElementById('numberWithCommas');
const button = document.getElementById('submitButton');
button.addEventListener("click", () => {
const number = document.getElementById('number').value;
answerElement.textContent = Number(number).toLocaleString();
})
You need to use Number(x) for it to work. Also, the variable number should be defined after the button press, each time.

How to create a form for comments with the ability of dynamically adding them to the list?

I need to create a form for comments with the ability to dynamically add them to the list. Each comment should have an assigned ID in consecutive order. The newest comment should be at the very bottom. Comments should be stored in the comments array. Each comment should have properties such as id (number) and text (string). Comments array must be empty when loaded initially. Each click on the "Add" button should create a new object inside the array and create element in the DOM tree.
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = commentForm.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.map(() => ({ id: 'nextId++', text: commentInput.value }));
}
createElement();
});
function createElement() {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = comments.text;
commentList.appendChild(newComment);
}
<!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" />
<title></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>
There are some issues in your code:
You are trying to access commentList from commentForm, but that element is outside of the commentForm. Use document object to access the element.
comments is an array from which you are trying to access text property, there is text property on comments.
You should pass the current input value to the function so that you can set the newly created LI's text with the value.
You should use push() instead of map() to push an item into the array. nextId is a variable but you are using that as if it is a string, you should remove the quotes around it.
For the better user experience, I will suggest you to clear the value of the input after creating the item.
Demo:
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = document.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.push({ id: nextId++, text: commentInput.value });
}
createElement(commentInput.value);
commentInput.value = '';
});
function createElement(ci) {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = ci;
commentList.appendChild(newComment);
}
<!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" />
<title></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button type="button" data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>

How can I combine two event functions of properties such as JavaScript?

var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
e.preventDefault;
question.innerHTML = input.value;
input.value = "";
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
/*
button.addEventListener("click",function(ev){
ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
}
else{
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
*/
<!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">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
I am sorry that I asked you a question using a translator because I can't speak English.
I have a question in the JavaScript code.
First, the first function is input the first word, and the event is click.
The second function is the same as the first letter of the word you received, and the last letter is the same, so you put the first letter in the first letter.
These two functions can be combined, but I think both functions are duplicated because they are event clicks.
How can i write code that combines two functions and performs sequential functions?
One Function Solution
There is no need for two functions, you can write it as one function. Consider here that you don't reset the input.value twice when you combine both. Just reset it at the end of the function.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", function() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
<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">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
Call Consecutively Wrapper Function
If you want to use two functions you can do a wrapper function and inside it you can call your two other functions.
Then when the button get's pressed you call the wrapper function which will proceed the two other functions consecutively.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", wrapperFunction);
function a() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
}
function b() {
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
}
function wrapperFunction() {
a();
b();
}
<!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">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
I removed the preventDefault, then I added a setTimeout to changing input.value so both functions can run(with the input.value resource shared)
Because setTimeout is asynchronous, it would work well in situations like this, since it would wait until the other things finish running(I'm paraphrasing so don't quote me) then it will run.. making both functions work at the "same time"
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
//e.preventDefault;
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
button.addEventListener("click",function(ev){
//ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "good"
input.focus();
}
else{
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "bad"
input.focus();
}
})
<!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">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>

Categories