应用onkeypress后获取字段值

时间:2011-11-28 15:55:10

标签: javascript javascript-events

我有一个javascript函数,可以确保用户只键入数字 我使用onkeypress="return onlyNumbers(event, 'MaxRate', 1300, 62500);"

来调用它
function onlyNumbers(evt, id, value, maxRange)
{
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    var answer = false;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    // if user provided id
    if(id)
    {
        // we obtain the new value
        var newValue = ( (document.getElementById(id).value) + String.fromCharCode(charCode) );
        // we check for range limits
        if(maxRange && newValue > maxRange)
        {
            return false;
        }

        // we check to see if value has changed, therefore we will highlight text
        if(value)
        {
            highlight_text_on_change(id, value, newValue);
        }
    }

    return true;
}

function highlight_text_on_change(id, value, newValue)
{
    if(newValue)
    {
        if(newValue == value)
        {
            document.getElementById(id+'_name').style.color = '';
        }
        else
        {
            document.getElementById(id+'_name').style.color = 'red';
        }
    }
    else
    {
        if(document.getElementById(id).value == value)
        {
            alert("UnHighlighting text");
            document.getElementById(id+'_name').style.color = '';
        }
        else
        {
            alert("Highlighting text");
            document.getElementById(id+'_name').style.color = 'red';
        }
    }
    return true;
}

该函数首先验证是否检查并查看用户是否按下了数字键,然后如果数字键的值已更改,则具有id+'name'的文本将文本颜色更改为红色表示它发生了变化。我唯一的问题是,假设文本字段的默认值是1300,如果用户键入6,则值更改为13006,或13060,或13600,或16300,或61300并且字段突出显示,但如果用户之后按下退格键,然后该字段不会突出显示,因为退格操作将无法正确注册。是否有任何方法我可以知道用户按下退格键的位置,或获取文本字段的新形成的值而不将其应用于texfield,直到我检查新值是否有效?

0 个答案:

没有答案