I’ve got problems with setting focus to an input field after validating it.
I’ve got two 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.
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:
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.