返回焦点并使用jquery选择文本



我正在验证html表单上的文本输入,如果文本无效,我希望集中并选择文本。

如果我的验证函数看起来像(只是一个例子):

jQuery.fn.DateHelper = function(text){
    return this.each(function(){
    //Make sure we're dealing with text-based form fields
    if(this.type != 'text')
    return;
    // call the processNumber function when the onBlur event is fired and there is a value in the field.
    $(this).blur(function() {
        if (this.value != '')                 
            processNUmber(this);
        });
    function processNumber( txtField ) {
        if (!isNan(txtField ))  {
            alert("not a number");
            this.focus(); // this does not work.
            // how to select text?     
        }
    }
};

在函数中传递txtField参数,在processNumber函数中使用它而不是this

function processNumber( txtField ) {
    if (!isNan(txtField ))  {
        alert("not a number");
        txtField.focus();   
    }
}

此外,您在jQuery.fn.DateHelper函数的.each()循环中声明processNumber函数,这不是必须的。您可以在.each()之外声明该函数,并且运行该插件的任何元素都可以访问该函数。

更新

然而,您的代码函数存在几个语法错误:

jQuery.fn.DateHelper = function(text){
    return this.each(function(){
        //Make sure we're dealing with text-based form fields
        if(this.type != 'text') return;
        // call the processNumber function when the onBlur event is fired and there is a value in the field.
        $(this).blur(function() {
            if (this.value != '') processNumber(this);//you were calling the processNUmber function, which doesn't exist
        }).focus(function () {
            this.select();
        });
        function processNumber( txtField ) {
            //isNan is broken: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN
            //also txtField is a DOM element, not a string
            txtField.value = txtField.value.replace(/[^0-9.]/g, "");
            if (txtField.value.length > 0)  {
                alert("not a number");
                txtField.focus();    
            }
        }
    });//this was omitted
};

下面是一个演示:http://jsfiddle.net/uQ45E/6/

最新更新