frankie
frankie

Reputation: 673

javascript length function throwing an error on text field

This is accurately reporting the length of the text field in the console.log but it is also throwing the error beneath the code on each keyup. Any thoughts?

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

And this is what I get in Chrome's console

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

Upvotes: 0

Views: 1010

Answers (4)

frankie
frankie

Reputation: 673

OK, it is solved. Thanks for the help. I noticed that the keyup was firing twice. And the error was being thrown the second time. When I looked closer at the HTML I saw that the parent was also using the ".search" class.

So here's my fix using a strong ID for the input field

$('#searchInputField').keyup(function () {
            var searchTerm = this.value;
            if (searchTerm.length > 2){
            getSuggestions(searchTerm);
            }else{
                $('#Button').click();
            }
        })

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388346

It is a blind answer, since you have to shared your html

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

Upvotes: 1

user571545
user571545

Reputation:

You could test the value of 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();
        }
    })

Upvotes: 0

benams
benams

Reputation: 4646

try to replace this.value.length with $(this).val().length

Upvotes: 2

Related Questions