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

时间:2012-01-18 21:07:15

标签: 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?     
        }

    }

};

1 个答案:

答案 0 :(得分:1)

在您的函数中,您传递txtField参数,在this函数中使用processNumber而不是function processNumber( txtField ) { if (!isNan(txtField )) { alert("not a number"); txtField.focus(); } }

processNumber

此外,您在.each()函数中的jQuery.fn.DateHelper循环内声明.each()函数(不一定是这种情况),您可以在{{1}之外声明该函数这个插件运行的任何元素都可以访问它。

更新

您的代码函数有多种语法错误:

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/