Input Validation onblur focus

4.6k views Asked by At

Having trouble getting this to work

  <script type="text/javascript">
  //<![CDATA[
  <!--
   function checkPrice(form) {
     var input=0;
     input=document.stickerPrice.value;
        if (input<100000) {               
            alert("Sticker price must be more than $100,000");
            document.getElementsByName("stickerPrice").focus();
    }
 }

       // -->
       //]]>
     </script>

and heres the label part.

   <form action=''>

    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this.formData)" /></p>
    </form>

I want an alert box to come up if its less than 10,000 with the onblur event and then place focus back onto that text box.

2

There are 2 answers

0
Ammar On

You can pass the input itself by calling

onblur="checkPrice(this.formData)"

then you can check for its value directly by calling

form.value

and focus by

form.focus();

here is a working sample.

function checkPrice(form) {
     var input=0;
     input=form.value;
        if (input<100000) {               
            alert("Sticker price must be more than $100,000");
            form.focus();
    }
 }
<form action=''>
    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this);" /></p>
    </form>

1
Luiz Nogueira On

I suggest you work-around and remove focus() with onblur.

function checkPrice(form) {
     var input=0;
     input=form.value;
        if (input<100000) {               
            alert("Sticker price must be more than $100,000");
            form.value='';            
    }
 }
 <form action=''>
    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this);" /></p>
    </form>