Why Onblur is not working (jQuery / Javascript)

I have the following input field for which I want to pull out sentences when the user types:

<input type = 'text' name= 'target' id='target' style='width:150px' onblur ='setTimeout('removeSuggestions()', 20);' onkeyup ='getSuggestions(this.value);'/> 

There are "suggestions" under it, and I use the following javascript.

 function getSuggestions(value){ if (value !=""){ $.post("target.php", {targPart:value}, function(data) { $("#suggestions").html(data); if(value.length>2){ doCSS(); } }); } else { removeSuggestions(); } } function removeSuggestions(){ $("#suggestions").html(""); undoCSS(); } function addText(value){ $("#target").val(value); } function doCSS(){ $("#suggestions").css({ 'border' : 'solid', 'border-width': '1px' }); } function undoCSS(){ $("#suggestions").css({ 'border' : '', 'border-width': '' }); } 

I suppose when I go out of bounds ... should the div sentences disappear or should I do it more explicitly?

Thanks!

+4
source share
3 answers

Your problem is here:

 <input type = 'text' name= 'target' id='target' style='width:150px' onblur ='setTimeout('removeSuggestions()', 20);' onkeyup ='getSuggestions(this.value);'/> 

For some reason, you use single quotes to surround your attribute values, but then you also use it to surround your function call in setTimout (). Therefore, when the browser parses it, it stops the attribute in

 onblur ='setTimeout(' 

And you get JS errors.

Use double quotes to surround your HTML attributes.

 <input type = "text" name= "target" id="target" style="width:150px" onblur ="setTimeout('removeSuggestions()', 20);" onkeyup = "getSuggestions(this.value);"/> 

Also, this is not the best way to use setTimout (). Use an anonymous function instead.

In addition, binding inline event listeners is not best practice. Use unobtrusive JavaScript instead.

 $(function(){ $('#target').blur(function(e) { setTimeout(function(){ removeSuggestions() }, 20); }); $('#target').keyup(function(e) { getSuggestions(e.target.value); }); }); 

hope that helps

+6
source

you have your single quotes inside other single quotes:

 onblur ='setTimeout('removeSuggestions()', 20);' 

must read

 onblur='setTimeout("removeSuggestions()", 20);' 

In addition, I would recommend not putting spaces between the attributes of the HTML tag and their values ​​(see the comment), this can cause problems with some browsers with strict parsers.

+4
source
 <input type = 'text' name= 'target' id='target' style='width:150px' onblur ="setTimeout('removeSuggestions()', 20);" onkeyup ='getSuggestions(this.value);'/> 

Since removeSuggestions should be treated as a literal, and therefore you should use a double quote for attribute values.

+1
source

All Articles