views:

567

answers:

4

Hello, I've got problems with setting focus to an input field after validating it.

I've got 2 fields: from and to.

   <spring:message code="template.fields.label.from"/>: 
       <mvc:input  path="templateFields.selectorRangeFrom" 
       onchange="validateNumber('templateFields.selectorRangeFrom',true)"/>
   <spring:message code="template.fields.label.to"/>: 
      <mvc:input path="templateFields.selectorRangeTo"   
     onchange="validateNumber('templateFields.selectorRangeTo',true)"/>

And I've got method validateNumber() which validates the field and returns false if the field is invalid, true otherwise. However the focus never stays on invalid number, it will always go the next object.

function validateNumber(index,isInteger) {
 var object = document.getElementById(index);
 var value = object.value;  
 if (testNumeric2(value,isInteger)==false)  {
  alert('Please correct the value: ' + value);     
  object.focus();
  object.select();
  return false; 
 } 
return true; 
 }

I have found out that if I add: event.returnValue=false (before returning false), then it works for IE. But I can't find the solution for Firefox.

Thanks for any suggestions, matali

A: 

I'm not sure what returning false for onChange is supposed to mean. If you merely wish to re-focus the problem area, I would suggest you do this via a setTimeout() call (you will have to create a closure around your input element).

This way the event handling will be complete when you attempt to focus the text box.

As a side note, I would also suggest you don't use alert() to notify the user of an error, since it is jarring, and can cause a harsh unexpected sound on many Windows systems. Displaying an icon next to, or a red border around the trouble control would probably be a much better way to treat the user.

levik
A: 

Thanks levik for your response. Yes you're right - I would like to re-focus the problem area. And I also agree that alert shouldn't be used, I just did it as a workaround because I couldn't set focus to this input box.

And could you be more specific about setTimeout() call?

matali
+1  A: 

setTimeout() allows you to defer the execution of a function for a number of milliseconds - if you use zero, this simply means, "do this as soon as you're done with whatever you're doing now" - handling the event, in your case.

Try this:

if (! /** check field **/) {
   /** show error **/
   setTimeout((function() { object.focus() }), 0);
}

Basically you would be creating a function that will focus your input box, and then instructing the browser to call it as soon as it's done doing the default handling of the event.

levik
A: 

Thanks, now it's clear.

matali