Javascript textfield值着重于

时间:2011-07-24 03:08:43

标签: javascript html css focus onblur

环境: 请使用IE进行测试

要求: 我有一条警告消息,检查用户输入的值是否小于8位 - 用户将无法移动到下一个字段....他应该保持在同一个字段上。

问题: 除了一件事之外,一切都很好用 - 当用户在少于8位的文本字段中输入任何值时,他会以这样的方式返回他的f,而不是光标移动到输入值的第一个字母,而它应该返回到输入值的最后一个字母。

代码:

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

1 个答案:

答案 0 :(得分:3)

这是一个黑客,但这很有效 - 添加一个onfocus监听器来替换它自己的值,IE将通过将光标放在末尾来表现 - onfocus="this.value = this.value;"

像这样使用:

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

如果您计划迁移到JQuery(我推荐),请查看此插件:

// 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);
相关问题