Reputation: 673
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
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
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
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