Issue
When the user clicks the buttons I want it to output the correct response.If the user puts 0 in the input box and then clicks the button I want it to say this is zero.If it 1 and higher I want it to say it positive number.If it -1 and lower it should say this is negative number.
<!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>numberCheck</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Number Check</h1>
<input type="number" id="num">
<button id="submit">Submit</button>
<div id="store"></div>
<script>
const num = document.getElementById('num');
const data = num.value
const btn = document.getElementById('submit');
const store = document.getElementById('store');
btn.addEventListener('click',()=>{
checker();
});
function checker(){
const ele = document.createElement('div');
if (data === 0){
ele.innerHTML =data+' this is a zero';
store.appendChild(ele);
}
if (data <0){
ele.innerHTML =data+' this is a negitive number';
store.appendChild(ele);
}
if (data >0){
ele.innerHTML =data+' this is a positive number';
store.appendChild(ele);
}
}
</script>
</body>
</html>
Solution
So first do not repeat yourself, if you want to create a new div and append it i'll recommend u to do it once in your function.
const ele = document.createElement('div');
store.appendChild(ele);
and because you are using input type number u have to get the value as integrer with valueAsNumber.
Then you have to update the value, yes because the value change while u are loading the value but never updating it.
By the way for a changing value u can't use const but need to use a let or var.
btn.addEventListener('click', function() {
let val = num.valueAsNumber;
checker(val);
});
Here is a working version of your code : https://jsfiddle.net/4a17fsbn/
Answered By - Asmir Belkic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.