3

So I have a calculator with an error message that displays, if they press the "calculate" button if the input is NaN. The error message keeps getting created everytime the user presses calculate. How do i make it so it only shows even after pressing "calculate" multiple times?

enter image description here

    function displayErr() {
    const formBox = document.querySelector("form");
    const errorBox = document.createElement("div");
    errorBox.className = "errorBox";
    const errorText = document.createTextNode("Those are not numbers!");
    errorBox.appendChild(errorText);
    formBox.appendChild(errorBox);
}

if ((isNaN(billInput)) || (isNaN(peopleAmount)) || (billInput === "") || (peopleAmount === "")) {
    displayErr();
}
  • 2
    Just have one div and show it when they click the button if the input is NaN, hide it when it is. You don't have to create a new div every time. – Axelle Sep 29 '20 at 12:02
  • i guess yea that's easier lol. Is there any way I can fix this tho with a loop or something? I am fairly new to JS. –  Sep 29 '20 at 12:04
  • if you want to create the div and not hide / show it for some reason you could use a boolean variable that gets updated to 1 when the div is created and back to 0 when it gets deleted again. Just add a check for the boolean value 0 to the start of the function (if !boolean continue function.. ) etc. – Warden330 Sep 29 '20 at 12:04
  • oh if you are new to JS my description is probably more confusing than helping. Let me know if you need an example – Warden330 Sep 29 '20 at 12:06
  • You definitely don't need a loop. You should go through these steps: > Is the input valid or not, if it is: check if the error div exists and delete it. If the input is not valid: > check if the error div already exists. If it already exists: delete it and add a new div. If it doesn't, just add a new div. However, if you don't mind hiding/showing, I would strongly suggest to just place an error div in your html and hide/show it if necessary. It's way more simple and there are a ton of existing examples. – Axelle Sep 29 '20 at 12:07
  • @AdrianB. If one one the 5 answers helped you, please consider upvoting/accepting the answer so other users can easily find a solution. Take a look at; [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – 0stone0 Sep 30 '20 at 13:33

5 Answers5

0

The most straightforward way is to check if the element already exists.

function displayErr() {
    // Get error element
    const errorElement = document.getElementsByClassName('errorBox');

    // If it already exists
    if (errorElement && errorElement.length > 0) {

        // Dont add another one
        return;
    }

    // Add new errorBox
    const formBox = document.querySelector("form");
    const errorBox = document.createElement("div");
    errorBox.className = "errorBox";
    const errorText = document.createTextNode("Those are not numbers!");
    errorBox.appendChild(errorText);
    formBox.appendChild(errorBox);
}

Another option would to be using css classes to 'hide' the element;

  1. Always render the element, but hide it with display: none
  2. In the displayErr(), make the element visible with something like document.getElementsByClassName('errorBox')[0].style.display = block;
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

a better way of doing this is to show and hide the element using CSS classes create the element and hide it using

display: none;

and show it by adding a class to the element

display: block;

 const element = document.getElementById("myDIV");
 const button = document.getElementById("btn");
 button.addEventListener("click", () => element.classList.toggle("show"));
 
#myDIV {
  display: none;
}

.show {
  display: block !important;
  }
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<button id="btn">Try it</button>

<div id="myDIV">
This is a DIV element.
</div>

</body>
</html>
MRsabs
  • 85
  • 3
  • be careful with arrow functions if you want it to run on IE11. otherwise this is a great approach. – Axelle Sep 29 '20 at 12:29
0

For what it's worth, here is a pure JavaScript example of a show/hide interpretation:

function CheckInput() {
    const billInput = document.getElementById("b").value;
    const peopleAmount = document.getElementById("p").value;

    if ((isNaN(billInput)) || (isNaN(peopleAmount)) || (billInput === "") || (peopleAmount === "")) {
    showErr();
  }
  else{
    hideErr();
  }
}

function hideErr(){
    console.log("hide");
    const el = document.getElementById("error");
    el.style.display = "none";
}
function showErr(){
    console.log("show");
    const el = document.getElementById("error");
    el.style.display = "block";
    el.innerHTML = "Hey sorry wrong input";
}

window.onload = function() {
    hideErr();
}

You can see the HTML and try the code here: https://jsfiddle.net/0mrx5ev7/

Axelle
  • 442
  • 1
  • 9
  • 24
0

You can pass a parameter to your displayErr function, then use it to set the hidden HTML attribute and textContent of a single target div, identified by its HTML id.

This way, the functionality becomes reusable, and you can set/unset the error message whenever you need.

const input = document.querySelector('#input')
const errDisplay = document.querySelector('#err-display')

function displayErr(msg) {
    errDisplay.textContent = msg || ''
    errDisplay.hidden = msg ? null : 'hidden'
}

input.addEventListener('input', () => {
    displayErr(isNaN(input.value) ? "Not a number" : null)
})
#err-display {
    font-family: sans-serif;
    background: red;
    color: white;
    margin: .5em 0;
    padding: .5em;
}
<input id='input' placeholder='Start typing'>

<div id='err-display' hidden></div>
Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27
-1

try to use a counter. like if int i == 0 --> do the function. i would do so

    int i = 0;

    function displayErr() {
    const formBox = document.querySelector("form");
    const errorBox = document.createElement("div");
    errorBox.className = "errorBox";
    const errorText = document.createTextNode("Those are not numbers!");
    errorBox.appendChild(errorText);
    formBox.appendChild(errorBox);
}

   if ((isNaN(billInput)) && i == 0 || (isNaN(peopleAmount)) && i == 0 || 
      (billInput === "") && i == 0 || (peopleAmount === "") && i == 0) 
{
    displayErr();
    i += 1;
}

now it will display an error only once, because i is never going to be 0 anymore