Thanks! I knew about the validate stuff, it was kind of a quick and
dirty example. But I appreciate your bringing it all to my attention.

The  jQuery docs for blus() say "the default action can be prevented
by returning false". Maybe it should be corrected.

Your suggestion of using setTimeout produces the desired results. Like
you said, not too pretty but effective.

Thanks!



On Sep 9, 7:40 pm, Mr Speaker <mrspea...@gmail.com> wrote:
> I think the problem is that according to the W3C standards, the blur
> event is not cancelable: They don't seem to want the programmer to be
> able to mess with a blur...
>
> But also, your validation code is a bit buggy anyway: the "ret"
> variable is undefined and the regex you use will only catch the cases
> where someone pastes in a tab or carriage return value - not if it's
> an empty field.
>
> Also also, I think if you call focus inside blur they sort of "fight"
> for control of the cursor! It seems to work if you put a slight delay
> on the event, like:
>
> function validateFld( fld ){
>         return fld.match(/\S/);
>
> }
>
> $( '#fld' ).blur( function(){
>         if ( !validateFld( $( this ).val() ) ){
>                 alert( 'invalid' );
>                 setTimeout( function(){
>                         $( '#fld' ).focus()
>                 }, 0 );
>         }
>
> });
>
> Not particularly attractive, but it works... I'm not sure if there's a
> nicer way to do it.
>
> On Sep 10, 9:49 am, jhm <jmay...@gmail.com> wrote:
>
> > I'm having trouble setting the input focus when validating fields in a
> > form. I have a very simple case below, that validates a field for
> > white space. If it has white space, it triggers an alert and I'd like
> > the focus to stay in that field. However, when tabbing, it moves to
> > the next field regardless.
>
> > I'm using the blur event to validate the field. I'm returning false
> > when it has white space. I've even tried forcing the issue by setting
> > the focus to the field, and that doesn't work either.
>
> > I must be misunderstanding something. Anyone able to set me straight?
>
> > TIA
>
> > ---- code section  ----
>
> > <head>
>
> > <script type="text/javascript" src="js/jquery.js"></script>
> > <script type="text/javascript">
>
> > $(document).ready( function() {
>
> >   function validateFld( fld )
> >   {
> >         var checkWhite = new RegExp(/[\r\n\t ]/);
>
> >         return( !checkWhite.test(fld) );
> >   }
>
> >   $('#fld').blur( function() {
>
> >     if ( !validateFld($(this).val()) )
> >     {
> >       alert('invalid field');
> >       ret = false;
> >       // $(this).focus();
> >     }
>
> >     return( ret );
> >   });
>
> > });
>
> > </script>
>
> > </head>
>
> > <body>
> >     <div>
>
> >       <h2>Field Test</h2>
> >       <input type="text" name="fld" value="" id="fld" /><br />
> >       <input type="text" name="fld2" value="" id="fld2" /><br />
>
> >     </div>
> > </body>
> > </html>
>
> > ---- code section  ----

Reply via email to