0

I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:


$('#fieldId').blur(function() {
    var fieldValue = $(this).val();
    if(fieldValue == null || fieldValue.length == 0) {
        $(this).addClass('error');
        // show error message
        $('#errorDivId')
            .text('You must enter a value in this field')
            .show();
        $(this).focus();
    }
    else {
        if ($(this).is('.error')) {
            $(this.removeClass('error');
            $('#errorDivId').hide()
        }
    }
});

It sort of works but it moves the cursor to the next field and not the one I refocused on.

0

2 Answers 2

3

You can try this:

$('#fieldId').blur(function(evt) {
  var fieldValue = $(this).val();
  if(fieldValue == null || fieldValue.length == 0) {
    $(this).addClass('error');
    // show error message
    $('#errorDivId')
        .text('You must enter a value in this field')
        .show();
    this.focus();
    evt.preventDefault();
  }
  else {
    if ($(this).is('.error')) {
        $(this.removeClass('error');
        $('#errorDivId').hide()
    }
  }
});

However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:

    var self = this;
    setTimeout(function() { self.focus(); }, 1);

It's kind-of a hack but it should also work.

edit — @Gus is right about which "focus()" to call

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

Comments

2

The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.

Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().

$('#fieldId').change(function() {
    var fieldValue = $(this).val(); 
    if(fieldValue == null || fieldValue.length == 0) {
        $(this).addClass('error');
        // show error message
        $('#errorDivId').text('You must enter a value in this field').show(); 
        this.focus(); 
    } else {
        if ($(this).is('.error')) { 
            $(this).removeClass('error');
            $('#errorDivId').hide() 
        } 
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.