Javascript长度函数在文本字段上抛出错误

javascript length function throwing an error on text field

本文关键字:出错 错误 字段 文本 函数 Javascript      更新时间:2023-09-26

这是在console.log中准确报告文本字段的长度,但它也在每个键上的代码下面抛出错误。任何想法吗?

$('.search').keyup(function () {
    var searchTerm = this.value;
            console.log(this.value.length);
            if (this.value.length>0){
            getSuggestions(searchTerm);
            }else{
                $('#Button').click();
            }
        })

这是我在Chrome的控制台得到的

Uncaught TypeError: Cannot read property 'length' of undefined pm_functions.js:283
(anonymous function) pm_functions.js:283
p.event.dispatch jquery.min.js:2
g.handle.h

尝试用$(this).val().length代替this.value.length

这是一个盲目的答案,因为你必须分享你的html

$('.search').keyup(function () {
    var searchTerm = $(this).val();
    if (searchTerm && searchTerm.length>0){
        getSuggestions(searchTerm);
    }else{
        $('#Button').click();
    }
})

好的,问题解决了。谢谢你的帮助。我注意到keyup发射了两次。第二次抛出错误。当我仔细查看HTML时,我发现父节点也使用了"。搜索"阶级。

这是我对输入字段

使用强ID的修复
$('#searchInputField').keyup(function () {
            var searchTerm = this.value;
            if (searchTerm.length > 2){
            getSuggestions(searchTerm);
            }else{
                $('#Button').click();
            }
        })

您可以测试this.value的值:

$('.search').keyup(function () {
var searchTerm = this.value;
        console.log(this.value.length);
        if ( (this.value.length>0) && (searchTerm !== null) ){
            getSuggestions(searchTerm);
        }
        else {
            $('#Button').click();
        }
    })
相关文章: