views:

193

answers:

3

I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?

$('input.IosOverrideTextBox').bind({
    blur: function(e) {
      var val = $(this).val();
      if (val.length == 0) return;
      var pval = parseTicks(val);
      if (isNaN(pval) || pval == 0.0) {            
        alert("Invalid override: " + val);
        return false;
      }
    },
    focus: function() {
      $(this).select();
    }
  });
A: 

I don't like forced focus, but can't you just focus after the blur takes place?

element.focus();

If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).

But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.

Matchu
A: 

You can do this with the validation plugin by default.

focusInvalid default: true

Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.

Then you'd only need to have the focus event handler do your select and let the plugin handle validation.

tvanfosson
I should have given more background. This validation is happening in a form that's polling every 5 seconds. With this in mind I'm not sure if a validation plugin would be a good fit here?
digitalsanctum
A: 

Try it and let let me know..

$('input.IosOverrideTextBox').bind({
blur: function(e) {
  var val = $(this).val();
  if (val.length == 0) return;
  var pval = parseTicks(val);
  if (isNaN(pval) || pval == 0.0) {            
    alert("Invalid override: " + val);
    $(this).focus();
    return false;
  }
},
focus: function() {
  $(this).select();
}

});

-Praveen

Rare Solutions
This doesn't work
digitalsanctum