tags:

views:

26

answers:

3

Check if zip is 5 digit number, if not then display 'zip is invalid'. I want to use onBlur event to trigger the display. But it's not working.

<script>
$(function(){

function valid_zip()
  {
  var pat=/^[0-9]{5}$/;
  if ( !pat.test(   $('#zip').val()   ) )
     {$('#zip').after('<p>zip is invalid</p>');}
  }

})
</script>

zip (US only) <input type="text" name='zip' id='zip' maxlength="5" onblur="valid_zip()">
+1  A: 
$('#zip').blur(function()
  {
  var pat=/^[0-9]{5}$/;
  if ( !pat.test(   $(this).val()   ) )
     {$(this).after('<p>zip is invalid</p>');}

})

you are now using jQuery, don't do inline coding...

<input type="text" name='zip' id='zip' maxlength="5" onBlur="valid_zip()">

should just be

<input type="text" name='zip' id='zip' maxlength="5">
Reigel
What's inline coding?
phil
writing something like `onBlur` inside the element is inline...
Reigel
I got you. It seems that avoiding inline coding is a consensus.
phil
+1  A: 

It should look more like this:

<script>
        $(function(){

                $("#zip").blur(function() {
                        var pat=/^[0-9]{5}$/;
                        if ( !pat.test( $('#zip').val() ) )
                            $('#zip').after('<p>zip is invalid</p>');
                });
        });
    </script>

    zip (US only) <input type="text" name='zip' id='zip' maxlength="5">
Bobby
Why prefer .blur() over adding onBlur event in `<input>`?
phil
@phil: Yes we do, if we use JQuery. ;)
Bobby
A: 

onblur should be all lowercase.

<input type="text" name="zip" id="zip" maxlength="5" onblur="valid_zip()">

Also, why are putting valid_zip inside $() - you can just do:

<script>
  function valid_zip()
  {
    var pat=/^[0-9]{5}$/;
    if ( !pat.test(   $('#zip').val()   ) )
    {
      $('#zip').after('<p>zip is invalid</p>');
    }
  }
</script>
Amarghosh
$() is shorthand for $(document).ready(). I just want the script to run after all DOM elements is ready.
phil
You're just declaring a function - not calling it; you can safely do it outside `$()`
Amarghosh
I have other scripts inside $() which are left out on purpose since it's not relevant to this specific discussion. So I need the function to be declared inside $().
phil