1

my textbox ALWAYS returns with field is not a number, even if it is.

HTML

<form name = garysForm>
Number of adults: <input type="number" size="6" id="ofAdults" name="adultBox" min="0" max="50" required><br>
Number of children: <input type="number" size="6" id="ofChild" min="0" max="50" required><br>
Date:<input type="text" name="date" id="datepicker" required><br>   
<Button type="button"   onclick="BookingFare(); return false;">Calculate</button><br>
</form>

Javascript

var field = document.forms["garysForm"]["adultBox"].value;

    if (isNaN(field.value)) {
            alert('Please enter a valid number');

        }
9
  • You're not selecting anything, the name is invalid as it's not quoted, and using document.forms is a really poor way to get an element that has an ID Commented Mar 18, 2015 at 23:40
  • 1
    Also, you're calling value TWICE, which is the real problem Commented Mar 18, 2015 at 23:42
  • It should be just if (isNaN(field)) { Commented Mar 18, 2015 at 23:42
  • tried that it doesn't help Commented Mar 18, 2015 at 23:46
  • and i honestly don't care if calling document.forms is a really poor way, that is not causing a problem.... Maybe you shouldn't be so condescending if you don't even give the correct solution ? Commented Mar 18, 2015 at 23:55

3 Answers 3

1

You're calling field.value when you've assigned value to field.

var field = document.forms["garysForm"]["adultBox"].value;

if (isNaN(field.value)) {

Try this instead:

var field = document.forms["garysForm"]["adultBox"];

if (isNaN(field.value)) {
Sign up to request clarification or add additional context in comments.

2 Comments

tried that it just breaks it so that it doesn't even relay a message back
Point me at a plunker
0

I solved it by using the .elements method.

var field = document.forms["garysForm"].elements["adultBox"].value;

Then, you need to consider that an SPACE is also considered a number reference. So I applied the following logic.

var field = document.forms["garysForm"].elements["adultBox"].value;
console.log(field)
if (field=='') {
    alert('Please enter a valid number');
}
else if (isNaN(field)) {
   alert('Please enter a valid number');
}
else {
   alert(field)
}     

DEMO

*Jquery is only used for demo purpose.

I hope you find this answer helpful. Thanks.

Comments

0

You can get the value of the adult box using its id:

var field = document.getElementById("ofAdults").value;

if (isNaN(field)) {
    ....

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.