I have an input here with no default value set for, and I want to console.log the inserted value of the input when the button is clicked, but each time I click on the button, it logs empty, and not the inserted value of the input.
What might I be missing here?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Box Creator</title>
<style>
</style>
</head>
<body>
<label>Please enter a color :
<input type="text">
</label>
<br><br>
<button>CREATE</button>
<script>
let value = document.getElementsByTagName("input").item(0).value ;
// let valuePart = value.split(",") ;
document.querySelector('button').onclick = function () {
console.log(value) ;
}
</script>
</body>
</html>
Here is the correct code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Box Creator</title>
<style>
</style>
</head>
<body>
<label>Please enter a color :
<input type="text">
</label>
<br><br>
<button>CREATE</button>
<script>
//let value = document.getElementsByTagName("input").item(0).value ;
// let valuePart = value.split(",") ;
document.querySelector('button').onclick = function () {
let value = document.getElementsByTagName("input").item(0).value ;
console.log(value) ;
}
</script>
</body>
</html>
In your script, the variable value is assigned the value in the beginning and not when the button is clicked. Move this code into the onclick handler.
document.querySelector('button').onclick = function () {
let value = document.getElementsByTagName("input").item(0).value ;
console.log(value) ;
}
You need to get the value when the user clicks. What you did in your code was just to take the value one time. This variable would not change . Try this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Box Creator</title>
<style>
</style>
</head>
<body>
<label>Please enter a color :
<input type="text">
</label>
<br><br>
<button>CREATE</button>
<script>
// let valuePart = value.split(",") ;
document.querySelector('button').onclick = function () {
let value = document.getElementsByTagName("input").item(0).value ;
console.log(value) ;
}
</script>
</body>
</html>
If you needed the value to be a global then you could also do this :
let value ;
document.querySelector('button').onclick = function () {
value = document.getElementsByTagName("input").item(0).value ;
console.log(value) ;
}
What you need to understand here is the scope and the lifecycle of a variable.
When you declare a variable like this
let value = document.getElementsByTagName("input").items(0).value
What you actually are doing is getting the value of the input element but only one time. That means that if the value of the input changes , it won't update the appropriate variable.
Related
I want the programme to get the biggest number that the user has enter in one of the input boxes and display the bigger number to the user.I would also like some improvements to my code. I would it also be possible to do it with one input box instead of two
<!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>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button >Submit</button>
<div id="store"></div>
<script>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
function max(){
const element = document.createElement('div');
const num1 = box1.value;
const num2 = box2.value;
if (num1<num2 ){
element.innerHTML= num2;
store.appendChild(element);
}
if (num2<num1){
element.innerHTML= num1;
store.appendChild(element);
}
}
</script>
</body>
</html>
First of all, ECMAScript comes with a Math.max() function, so there is no need to re-implement that comparison logic.
Also, your max function doesn’t run automatically. You need to register it as an event listener on the “Submit” button using addEventListener and the click event in order to have it invoked upon clicking the button.
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
const button = document.getElementById('submit');
// upon clicking on the button …
button.addEventListener('click', () => {
max(); // … run `max()``
});
function max() {
const element = document.createElement('div');
element.innerText = Math.max(box1.value, box2.value);
store.appendChild(element);
}
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button id="submit">Submit</button>
<div id="store"></div>
Of course, there is not yet a validation that checks if the given values are actually numbers.
I don’t understand your request about doing it with only “one input box”, though, as determining the larger number (out of many) implies having more than one input, so please specify. Do you mean “multiple values in one input box” like comma-separated?
Yes, you can do it all in one input please see the code below
<!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>Get largest number</title>
</head>
<body>
<input type="text" class="myinput" placeholder="Enter your numbers seperated by commas only">
<button class="submit">Get Max</button>
<h1 class="output"></h1>
<script>
const inputElement = document.querySelector('.myinput');
const submitButton = document.querySelector('.submit');
const outputElement = document.querySelector('.output')
submitButton.onclick = function(){
let inputValue = inputElement.value;
if(inputValue !== ''){
try{
let numbers = inputValue.split(',').map(e=>eval(e));
const maxNumber = Math.max(...numbers);
outputElement.innerHTML = 'Largest Number: ' + maxNumber;
}catch(e){
outputElement.innerHTML = 'Incorrect input format!';
}
}
}
</script>
</body>
</html>
The code takes comma separated input from the user and converts it into an array using the split function. Each value separated by the comma will be an array item. I also mapped it to convert the numbers that were in string form to integer form using the eval function. then I used the try catch block to detect any input format errors that may occur that the program will not be able to process and push an error to the user that they have used the incorrect format.
I hope that helps alot!
i'm trying to get value of input field, so depending on if the input value is 0 or 1, the value of the input is one or two, and it's supposed to show up in console.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>demo</title>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<p>Input 0 or 1.</p>
<input id="ok" type="text">
<button onclick="functionn()"></button>
<script>
var x = document.getElementById("ok").value;
function functionn() {
if (x == 0) {
ok = "one";
console.log(ok); }
else if (x == 1) {
ok = "two";
console.log(ok);
} else {
alert("please input 0 or 1");
}
}
</script>
</body>
</html
You are so close!
The problem that you have is the "x" variable, it holds the value on the input after the page was loaded, which is and empty string.
You need to put that variable inside the function, so every time you click the button you will "go" and check the value of the input and then store it inside the "x" variable.
Hope this help! =]
try it:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>demo</title>
<meta charset="utf-8" />
<style></style>
</head>
<body>
<p>Input 0 or 1.</p>
<input id="ok" type="text" />
<button onclick="functionn()"></button>
<script>
var x = document.getElementById("ok");
function functionn() {
if (x.value === "0") {
ok = "one";
console.log(ok);
} else if (x.value === "1") {
ok = "two";
console.log(ok);
} else {
alert("please input 0 or 1");
}
}
</script>
</body>
</html>
This is the method which I tried. I've added a feedback just to test out if the JavaScript variable siteName contains the value from the HTML textbox value but it reflected "[object HTMLInputElement]" instead. Any idea why?
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName = document.getElementById('firstid');
function myFunction() {
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>
You have to use the value property to get the actual text from the input. Otherwise it will return the reference of the input text field. The reference is type of HTMLInputElement which has a value property holding actual data entered in the text field.
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName;
function myFunction() {
siteName = document.getElementById('firstid').value;
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
Use the value of the input element to retrieve from value form it, or else you will be getting an object.
document.getElementById("2ndid").innerHTML = siteName.value;
This is a pretty simple fix, you just have to add the value property at the end of the second fucntion.
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName.value;
}
You are not initialising your variable.
here a working code.
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName;
function myFunction() {
siteName= document.getElementById('firstid').value;
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>
I made a simple HTML with JS inside, and its about add 1 to variable and keep running until user gets 1 by rng(random number generator). Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function clicked(){
var num = Math.floor((Math.random() * 100) + 1);
var click = 0;
click = click+1;
if(num == 1){
document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
document.getElementById("press").disabled = true;
}
else{
document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
}
}
</script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
<input type="button" value="Press Me!" id="press" onclick="clicked()">
<div id="print"></div>
</body>
</html>
At this code, click = click+1 don't work and click is stuck at 1. What should I do?
The reason your click stuck to 1 is whenever function called you are declaring
click = 0, so it is initialized every time you press the button. So just declare var click outside of function clicked() and see the magic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
var click = 0;
function clicked(){
var num = Math.floor((Math.random() * 100) + 1);
click = click+1;
if(num == 1){
document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
document.getElementById("press").disabled = true;
}
else{
document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
}
}
</script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
<input type="button" value="Press Me!" id="press" onclick="clicked()">
<div id="print"></div>
</body>
</html>
I cannot get value of input, why? Thanks for your answer!
This is the code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input id="fullname"/>
<button id="button">button</button>
</body>
<script>
var name = document.getElementById("fullname").value;
var btn = document.getElementById("button");
btn.onclick = function(){alert(name)};
</script>
</html>
Script tag need to be in the body tag
You need to get the value when you have entered it
Working plunk
<script>
var btn = document.getElementById("button");
btn.onclick = function(){
var name = document.getElementById("fullname").value;
alert(name);
};
</script>