Значение текстового поля Javascript сфокусировано на - PullRequest
3 голосов
/ 24 июля 2011

Окружающая среда: Пожалуйста, используйте IE для тестирования

Требования: У меня есть предупреждающее сообщение, которое проверяет, вводит ли пользователь значение меньше 8 цифр - пользователь не сможет перейти к следующему полю ... он должен остаться в том же поле.

Проблема: С функциональностью все в порядке, кроме одного - когда пользователь вводит любое значение в текстовое поле длиной менее 8 цифр, он возвращает свои ошибки таким образом, что курсор перемещается на первую букву введенного значения, тогда как он должен возвращаться к последняя буква введенного значения.

Код:

<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 Ответ

3 голосов
/ 24 июля 2011

Это хак, но это работает - добавьте слушатель 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);
...