Prasad_Joshi Prasad_Joshi - 20 days ago 5
Javascript Question

why the if..else block works only for one time

I need to check each time before user press "add" button to check if data is entered or not, but my "if...else" block works only one time after that it start accepting blank entries in array..I'm not sure why it fails the next time. any help is appreciable as I'm new to java script.
here is my code snippet.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Click the button to add a new el</title>
</head>

<body>

<label>Enter an New item to add in Stock</label>
<br>
</br>
<input type="text" name=" itemName" id="addItemInStock"></input>
<br></br>
<p id="errorMsg"></p>

<button onclick="addToStock()">Add</button>

<p id="showList"></p>
<p id="listCount"></p>


<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");


function addToStock() {
if ((newItem.value) === "") {
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";

} else {
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
document.getElementById("showList").innerHTML = fruits;

clearAndShow();
}
}

function clearAndShow() {
newItem.value = " ";
}
</script>

</body>

</html>

Answer

Your clearAndShow function sets the input elements value to a single space, but the if checks for an empty string.

You also set the display to none the first time it shows, but never switch it back to block

var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("showList").innerHTML = fruits;
    var newItem = document.getElementById("addItemInStock");


    function addToStock() {
      if ((newItem.value) === "") {
        document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
        document.getElementById("errorMsg").style.display = "block";
      } else {
        document.getElementById("errorMsg").style.display = "none";
        fruits.push(newItem.value);
        document.getElementById("showList").innerHTML = fruits;

        clearAndShow();
      }
    }

    function clearAndShow() {
      newItem.value = "";
    }
<label>Enter an New item to add in Stock</label>
  <br>
  </br>
  <input type="text" name=" itemName" id="addItemInStock"></input>
  <br></br>
  <p id="errorMsg"></p>

  <button onclick="addToStock()">Add</button>

  <p id="showList"></p>
  <p id="listCount"></p>

Comments