Search code examples
javascripthtmlcssfocusonblur

Javascript textfield value focus on


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>

Solution

  • 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:

    <input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" />
    

    If you ever plan to migrate to JQuery (which I recommend), check out this plugin:

    // jQuery plugin: PutCursorAtEnd 1.0
    // http://plugins.jquery.com/project/PutCursorAtEnd
    // by teedyay
    //
    // Puts the cursor at the end of a textbox/ textarea
    
    // codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
    (function($)
    {
        jQuery.fn.putCursorAtEnd = function()
        {
        return this.each(function()
        {
            $(this).focus()
    
            // If this function exists...
            if (this.setSelectionRange)
            {
            // ... then use it
            // (Doesn't work in IE)
    
            // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
            var len = $(this).val().length * 2;
            this.setSelectionRange(len, len);
            }
            else
            {
            // ... otherwise replace the contents with itself
            // (Doesn't work in Google Chrome)
            $(this).val($(this).val());
            }
    
            // Scroll to the bottom, in case we're in a tall textarea
            // (Necessary for Firefox and Google Chrome)
            this.scrollTop = 999999;
        });
        };
    })(jQuery);