algorithmicCoder algorithmicCoder - 2 months ago 14
CSS Question

Why is Onblur not working (JQuery/Javascript)

I have the following input field for which i want to pull suggestions when a user types:

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


There is a "suggestions" div below it and I am using 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 figure that when i click outside the field....the suggestions div should vanish or do i have to do it more explicitly?

Thanks!

Answer

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 are using single quotes to surround your attribute values, but then you are also using it to surround your function call in setTimout(). So when the browser parses it, it stops the attribute at

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, that's not the best way to use setTimout(). Use an anonymous function instead.

Also, binding event listeners inline is not a best practice. Instead use unobtrusive JavaScript.

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

    $('#target').keyup(function(e) {
        getSuggestions(e.target.value);
    });
});

hope that helps