Home > Software engineering >  How to add an if statement to check multiple variables in a function (Javascript)
How to add an if statement to check multiple variables in a function (Javascript)

Time:11-10

This block of code in my HTML doc serves as a function to perform a calculation. It prompts the user to enter the number of rooms and total sq. ft., then multiplies the sq ft by 5 to get the estimate. I am trying to figure out how to add an if-statement to serve as an error message if a user inputs a negative number. Below is the function copied from the code. Would I add it directly in the function, before or after it? What I basically want to say is,

if (var a && b <= 0) {
print "Invalid entry. Please reload the page and enter a positive number." } 

How would I go about doing this in JavaScript? Also, is there a better way to ask the user than using < p> < /p>?

<div class="container-fluid">
    <p>Please enter the number of rooms affected, and the total square foot. </p>
    <input type="text" name="numRooms" id="numRooms"> <br>
        
    <input type="text" name="roomSize" id="roomSize"><br>
    <button type="button" onclick="submit1()">submit</button><br>

    <p id="result"></p>
</div>

<script>
    function submit1(){
        var a =  document.getElementById("numRooms").value;
        var b =  document.getElementById("roomSize").value;
        var c =  parseInt(b) * 5; 

        document.getElementById("result").innerHTML="Your estimate is : $"   c;
    }
    </script>

CodePudding user response:

You could check the values in advance and exit early, if an error occurs.

function submit1() {
  var a =  document.getElementById("numRooms").value; // get a number with  
  var b =  document.getElementById("roomSize").value;
  var c = parseInt(b) * 5;

  if (isNaN(a) || a <= 0 || isNaN(b) || b <= 0) { // check if number or smaller/eq than zero
      document.getElementById("result").innerHTML = '<span style="color: #b00;">Please insert only positive numbers.</span>';
      return;
  }

  document.getElementById("result").innerHTML = 'Your estimate is : $ '   c;
}
<div class="container-fluid">
  <p>Please enter the number of rooms affected, and the total square foot. </p>
  <input type="text" name="numRooms" id="numRooms"> Rooms<br>
  <input type="text" name="roomSize" id="roomSize"> Size [sq ft]<br>
  <button type="button" onclick="submit1()">submit</button><br>
  <p id="result"></p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related