-1

I have started a new JavaScript task, which tells me to validate a form with a field and a button. Whenever I type in a random number, an alert box should appear with an answer 'The number is bigger/smaller than 10'. So far so good-I did that part of the task. The problem appears, when I type in the letter-the alert box appears anyway. How could this be fixed?

Code looks like this:

function validate(){
    x=document.myForm
    txt=x.myInput.value
    if (txt>=10)

    {
        alert("Number is bigger than 10")
        return true

    }

    else

    {
        alert("Number is smaller than 10")
        return false
    }

}

<form name="myForm" onsubmit="return validate()">
Enter a number: 
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">

Thank you for your answers!

user2145944
  • 3
  • 1
  • 2

2 Answers2

-1

You can use parseInt.

txt = parseInt(x.myInput.value,10);
Jeff Shaver
  • 3,315
  • 18
  • 19
-1

You could add one more else if statement to your code like below:

x=document.myForm.myInput.value;

else if(isNaN(x))

    {
        alert("Number cant be alphabet")
        return false
    }

Below is the Full Script

<script>
            function validate(){
    x=document.myForm.myInput.value;

    if (x >=10)

    {
        alert("Number is bigger than 10")
        return true

    }

    else if(isNaN(x))

    {
        alert("Number cant be alphabet")
        return false
    }
    else

    {
        alert("Number is smaller than 10")
        return false
    }

}
    </script>
defau1t
  • 10,593
  • 2
  • 35
  • 47