0

So I'm trying to take an element submitted into an input field and return a result using if else statements but it keeps returning my "else" statement no matter what. I used a w3schools project to begin with, but I can't seem to see what is going wrong.

The user will put a number is the "numSpots" input field and depending on the value of the number, an adaSpots value will get returned in the paragraph id="demo"

Here is my code

function myFunction() {
  var numSpots = document.getElementById("numSpots");
  var adaSpots;
  if (numSpots < 25) {
    adaSpots = "1";
  } else {
    adaSpots = "267";
  }
  document.getElementById("demo").innerHTML = adaSpots;
}
<p>Click the button to display a time-based greeting:</p>
<input type="number" name="numSpots" id="numSpots" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

1
  • 1
    you are getting element ..you need to get its value Commented Apr 15, 2016 at 12:24

2 Answers 2

1

you need to get the value of #numbSpots by document.getElementById("numSpots").value

function myFunction() {
  var numSpots = document.getElementById("numSpots").value;
  var adaSpots;
  if (numSpots < 25) {
    adaSpots = "1";
  } else {
    adaSpots = "267";
  }
  document.getElementById("demo").innerHTML = adaSpots;
}
<p>Click the button to display a time-based greeting:</p>
<input type="number" name="numSpots" id="numSpots" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much!! I can't believe I forgot the .value
glad to help, feel free to check the green check button :)
0

Try this ;)

You need to use parseInt function to convert string into integer value as text field value is returned as string; and you forgot to get the value using value property;

function myFunction() {
  var numSpots = document.getElementById("numSpots").value;
  var adaSpots;
  if (parseInt(numSpots) < 25) {
    adaSpots = "1";
  } else {
    adaSpots = "267";
  }
  document.getElementById("demo").innerHTML = adaSpots;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.