首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jquery返回焦点并选择文本

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

Stack Overflow用户
提问于 2012-01-19 05:07:15
回答 1查看 431关注 0票数 0

我正在验证html表单上的文本输入,并希望重点和选择文本,如果它是无效的。

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

代码语言:javascript
复制
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?     
        }

    }

};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-19 05:09:42

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

代码语言:javascript
复制
function processNumber( txtField ) {
    if (!isNan(txtField ))  {
        alert("not a number");
        txtField.focus();   
    }
}

您还可以在jQuery.fn.DateHelper函数的.each()循环内声明processNumber函数,但不必如此,您可以在.each()外部声明该函数,任何运行此插件的元素都可以访问该函数。

更新

您的代码可以工作,但是有几个语法错误:

代码语言:javascript
复制
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/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8917422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档