I am facing a problem while want to, output=pick "Positive","Negative","Zero" as message if number(user puts in input box) is + or - or 0, respectively.
I am writing code- but unable that Zero is coming in message everytime, whether putting anything.
I am writing this
var n1 = Number(number.value)
var finalresult;
if (n1 > 0) {
finalresult = `Positive`
} else if (n1 == 0) {
finalresult = `Neutral`
} else {
finalresult = `Negative`
}
function know() {
document.getElementById("result").innerText = finalresult
}
<input type="text" id="number"></input>
<button id="btn" onclick=know()>Know</button>
<p id="result"></p>
you have to recover the value of number input after it was updated
after a click on button or change event on input
function know(){
var n1=parseInt(document.getElementById('number').value);
var finalresult;
if(n1>0)
{finalresult=`Positive`}
else if(n1==0)
{finalresult=`Neutral`}
else
{finalresult=`Negative`}
document.getElementById("result").innerText=finalresult
}
<input type="text" id="number" ></input>
<button id="btn" onclick=know()>Know</button>
<p id="result"></p>
You need to put the JavaScript code into the know() function, so that the code is ran everytime the button is clicked and the know() function is triggered. In your question, finalresult is set when the input has no value (an empty string) and as '' is cast to 0 when using ==, '' == 0 returns true.
<input type="text" id="number" />
<button id="btn" onclick="know()">Know</button>
<p id="result"></p>
<script>
function know() {
var number = +document.getElementById("number").value;
var finalresult;
if (number > 0) {
finalresult = `Positive`;
} else if (number == 0) {
finalresult = `Neutral`;
} else {
finalresult = `Negative`;
}
document.getElementById("result").innerText = finalresult;
}
</script>
P.S. You could always consider using === instead of == ('' === 0 returns false).
function know() {
var n1 = +document.getElementById("number").value;
var finalresult;
if (n1 > 0) {
finalresult = `Positive`
} else if (n1 == 0) {
finalresult = `Neutral`
} else {`enter code here`
finalresult = `Negative`
}
document.getElementById("result").innerText = finalresult;
}
<input type="text" id="number"></input>
<button id="btn" onclick=know()>Know</button>
<p id="result"></p>