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.
Related
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 :)))
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)
});
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>
I have a difficult question, I am trying to get the input value of an input field, however, I need this to happen within another function.
I already have code that works outside of this other function but I need to refactor it to work inside another function that I am calling.
Examples of working code and non-working code are below.
Here is the HTML where I am getting the input:
<!DOCTYPE HTML>
<HTML>
<head>
<title></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/styles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript">
(function () {
var config = {
baseUrl: "js",
};
var dependencies = ["otherFile"];
require(config, dependencies);
})();
</script>
</head>
<body>
<div>
<label>Input URL</label>
<input type="url" />
<p id="targetInput"></p>
</div>
</body>
</html>
Here is the non-working JS that I am trying to call within another function:
function someOtherFunction() {
var getCurrentInput = function() { };
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
var getCurrentInput = function (e) {
log.currentInput = e.target.value;
};
}
});
Lastly here is the working code that works outside of the scope of someOtherFunction
var getCurrentInput = "";
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
function getCurrentInput(e) {
log.currentInput = e.target.value;
}
Now you may notice that there isn't a form being submitted here, the reason for this is because this code is running on an iframe that is being called into another app. The submit is happening there but requires me to call a function to make it happen and technically isn't a submit, meaning I don't have control over it like a regular submit. This is why I need to call the current input value inside someOtherFunction.
Any help would be greatly appreciated here! Essentially I want to get the value inside the input and update my API with the value as a JSON string. There must be a better way!
Was a bit difficult to follow at first given the nesting, but something like this?
const doThing = (e) => {
let input = document.getElementById("input");
let log = document.getElementById("targetInput");
log.textContent = input.value;
}
<div>
<label>Input URL</label>
<input type="url" id="input"/>
<p id="targetInput"> </p>
</div>
<button onclick="doThing()">Click</button>
Essentially an external submit that takes an internal input value, and injects it into another internal element?
So here is the problem.I want user to enter number of index in text box for array. After taking index i want user to enter value from a prompt box to store in that array but that prompt box is coming over and over again and i have to click on button every time to take input
Here is the code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Java Script:
var data = document.getElementById("t1").value;
function record(){
var crap = new Array(data);
for(var i=0;i<crap.length;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
In your case, you are retrieving data outside the function. Thus its value will be 'undefined' and the crap will became the array of one value that is undefined. So crap.length will be always 1.
Try this:
function record(){
var data = document.getElementById("t1").value;
var crap = []
if(crap != undefined)
for(var i=0;i<data;i++){
var tmp = prompt("Add something in my array","");
crap.push(tmp);
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
Enjoy coding ....
Try this,This will solve your issue.
You are just declaring an array named crap, and you are trying to get the crap.length even before the array is filled, so you are getting the issue. Since data has your value try looping with data value.
function record(){
data = document.getElementById("t1").value;
var crap = new Array(parseInt(data)); // you should take data here, since crap is empty at this point.
console.log(data)
for(var i=0;i<data;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Please run the code snippet and check the answer.