简体   繁体   中英

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.

Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?

 function add7() { let number = document.getElementById('num').value; let addition = 7; if (isNaN(number)){ document.getElementById("add").innerHTML ="Please enter a value"; } else { let original = parseInt(number,10); num = addition + original; document.getElementById("add").innerHTML = num; } }
 <div class="add"> Add 7 to the number <br> <input type="number" id="num"> <button onclick="add7()">Press Button</button> <hr> <p id="add"></p> </div>

That is because an empty string actually returns true when passed to isNaN() , ie isNaN('') returns true .

To do that, you can simply move the check to the final step, aka evaluate the num variable instead:

 function add7() { let number = document.getElementById('num').value; let addition = 7; let original = parseInt(number, 10); let num = addition + original; if (isNaN(num)) { document.getElementById("add").innerHTML = "Please enter a value"; return; } document.getElementById("add").innerHTML = num; }
 <div class="add"> Add 7 to the number <br> <input type="number" id="num"> <button onclick="add7()">Press Button</button> <hr> <p id="add"> </p> </div>

Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:

 function add7() { let number = parseInt(document.getElementById('num').value, 10); if (isNaN(number)) { document.getElementById("add").innerHTML = "Please enter a value"; return; } let addition = 7; let num = addition + number; document.getElementById("add").innerHTML = num; }
 <div class="add"> Add 7 to the number <br> <input type="number" id="num"> <button onclick="add7()">Press Button</button> <hr> <p id="add"> </p> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM