0

I have a JavaScript function in my head part of my HTML

<script>
   function validateForm() 
   {
     var apple = document.getElementById('apple').value;
     var err = 0;
     if (isNaN(apple)) {
        err += 1;
    }
    if (err != 0) {
        alert('Please check your input!');
        return false;
    } 
    else 
        return true; 
}
</script>

The form is shown below:

 <form name="orderForm" onSubmit="return validateForm();" method="post">  
    <div class="input-control text span5">
          <input class="span5" type="text" placeholder="Each @ $4.9" id="apple" name="apple" onChange='checkApple(this.value)'>
    </div>
  </form>

all brackets are completed and there is no typo.

When I submit the form with non numerical values, the form still gets submitted instead of error. May I know what's wrong with this ?

3
  • Have you tried not using JavaScript? <input type="number" .../> Commented Aug 30, 2013 at 12:19
  • use <script type="text/javascript"> instead of <script> Commented Aug 30, 2013 at 12:21
  • 1
    @Puneet It appears that the code is in HTML5, so no. Commented Aug 30, 2013 at 12:54

3 Answers 3

1

You need to accept an event:

function validateForm(e) {

And prevent it:

if (err != 0) {
    e.preventDefault()
    ...

On an unrelated note, I would suggest that you restructure your code so it is less complicated, like:

var apple = document.getElementById('apple').value;
if (isNaN(apple)) {
    ...

No need for an err variable.

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

2 Comments

Wait what? Since when was "some string" not NaN (ie. a number)?
@Kolink Fixed (again)
0

you must have input type="submit" or a button type="submit" in order for the onsubmit to trigger

1 Comment

Without it also submitted.
0

If your trying to perform a check for whether the input is a number, this may work:

function validateForm() 
{
     var apple = document.getElementById('apple').value;
     var err = 0;
     if (!isNaN(parseFloat(apple)) && isFinite(apple)) {
        err += 1;
     }
     if (err != 0) {
        alert('Please check your input!');
        return false;
     } 
     else 
        return true; 
}

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.