views:

41

answers:

3

Thanks guys. I take your advice and modify the script as following. Now it seems working.

<script src="jquery-1.4.2.min.js" type="text/javascript"></script>   
<script>
$(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">
A: 

zip is invalid should be enclosed in quotes

and .val needs to be .val()

<script>
  pattern=/^[0-9]{5}$/;
  if (!pattern.test( $('#zip').val() ) ) 
  {
    $('#zip').val($('<p>',{html: "zip is invalid"}));
  }
</script>
Dan Heberden
`.append()` on `<input>` element?
Reigel
oh.. yeah, i was just looking at the structure of it.. i'll adjust the code, good eye!
Dan Heberden
A: 

Space it out so you can see what's wrong..

pattern=/^[0-9]{5}$/;
if (
   !pattern.test(   $('#zip').val()  ) 
)
{
    $('#zip').after(
         $('<p>',{html: "zip is invalid"})
    );
}

val() and "zip is valid". Also, the var is useless unless within a function scope.

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

Now pattern is local to that function only and nothing else. In CMS's example it's still a global unless you're taking the snippet and using it in an actual function.

meder
`.append()` on `<input>` element?
Reigel
+2  A: 

.val needs to be .val()
and use .after() or .before() and not .append()

var pattern = /^[0-9]{5}$/;
if (!pattern.test($('#zip').val())) {
  $('#zip').after('<p>zip is invalid</p>');
}
Reigel
+1 You got it, makes no sense to `append` anything to an `input` element...
CMS