Environment:
Please use IE for testing it
Requirement:
I have an alert message which checks if user enters a value less than 8 digit – user wont be able to move to next field….he should remain on same field.
Problem:
Everything is fine with the functionality except one thing – when user enters any value in a textfield less than 8 digits he gets his foucs back in such a manner than the cursor moves to the first letter of the entered value whereas it should go back to the last letter of the entered valued.
Code:
<html>
<body>
<script>
function checkField(field) {
if (field.value.length < 8) {
// Toggle the active element's blur off and back on after the next blur
var active = document.activeElement;
if (active && active !== field) {
var blur = active.onblur || function(){};
active.onblur = function(){ active.onblur = blur };
}
field.focus();
alert("cannot be less than 8 digits");
}
}
</script>
<input type="text" id="test1" onblur='return checkField(this);'>
<br/>
<input type="text" id="test2" onblur='return checkField(this);'>
</tr>
</table>
</body>
</html>
It’s a hack, but this works – add an onfocus listener to replace the value with itself, and IE will behave by putting the cursor at the end –
onfocus="this.value = this.value;":Used like this:
If you ever plan to migrate to JQuery (which I recommend), check out this plugin: