I am having some problems with a javascipt function which I’m working on.
Here is what I am trying to do with the function:
I have a table element with a given value, and when there is a click on it, it calls my javasript function which is supose to appendChild an INPUT element with the value of the element, so the user can change that value. I want the INPUT element to call a function whit the onblur() event, so the modified value could be display again on the table element.
My problem is that the element does not respect the onblur() event. The function is executed right after the Input element is created, and does not wait to be an onblur() event.
Here is the code of the two functions:
var elemento = true;
function prueba(clave,cantidad) {
if(elemento){
var percent = document.getElementById('porciento' + clave);
percent.innerHTML = "";
var input = document.createElement("input");
input.setAttribute('type','text');
input.setAttribute('size','5');
input.setAttribute('value',cantidad);
input.setAttribute('id','child'+clave);
percent.appendChild(input);
input.focus();
child = document.getElementById("child" + clave);
child.onblur = blurPrueba();
}
}
function blurPrueba() {
if(elemento)
alert("Hello");
}
The alert is displayed without being an onblur()
Does anyone knows why this is happening???
Your problem is:
child.onblur = blurPrueba(), where you executeblurPruebaimmediately. Should be a reference:child.onblur = blurPruebaChanging the line, you tell the browser: “on blur for the child element, activate the
blurPruebafunction”.If you use
blurPrueba()you activate the function and assign it’s result to the blur event,blurPrueba()doesn’t return anything. So your line actually says: “onblur = undefined”In summary, if you want the browser to handle an event (here
blur) you need to provide a reference to the handler function (hereblurPrueba).