开发者

Creating an element and adding it an event in Javascript

I'm having problems adding an event to a dynamically created element in Javascript. This is the code:

var monto=document.createElement('input');
monto.type='text';
monto.name='monto'+cantpagos;
monto.id='monto'+cantpagos;
if(monto.addEventListener) monto.addEventListener("blur", sumpagos, false);
else if(monto.attachEvent) monto.attachEvent("onblur", sumpagos);
document.getElementById('pagos').appendChild(monto);

However it's not working, once I remove the focus the function is not called. What am I doing wrong? Thanks beforehand.

EDIT: This is more relevant code:

function sumpagos()
{
   var total=0;
   for(var i=1;i<=cantpagos;i++)
   {
      total+=document.getElementById('monto'+i).value;
   }
   document.getElementById('total').innerHTML="$"+total;
}

function addpago()
{
var i = 0;
var cuota=document.createElement('select');
cuota.name="cuota"+cantpagos;
cuota.id="cuota"+cantpagos;
for(i=1;i<=3;i++)
{
   cuota.options[i-1]=new Option("Cuota "+i, i);
}
document.getElementById('pagos').appendChild(cuota);
var monto=document.createElement('input');
monto.type='text';
monto.name='monto'+cantpagos;
monto.id='monto'+cantpagos;
if(monto.addEventListener) monto.addEventListener("blur", sumpagos, false);
else if(monto.attachEvent) monto.attachEvent("onb开发者_开发技巧lur", sumpagos);
document.getElementById('pagos').appendChild(monto);
document.getElementById('pagos').innerHTML+="<br />";
cantpagos++;
}

<td id="total">
$0
</td>

<input type="button" name="maspago" value="Añadir un Pago" onclick="addpago();" />
<input type="button" name="memospago" value="Eliminar un Pago" onclick="deletepago();" />
<div id="pagos"></div>


Here, this should make it work:

function sumpagos() {
    var total = 0,
        monto;

    for(var i=1; i <= cantpagos; i++) {
        monto = document.getElementById('monto' + i);
        if ( monto != null ) {
            total += +monto.value;
        }
    }    
    document.getElementById('total').innerHTML = '$' + total;
}

Try this:

var monto = document.createElement('input');
monto.type = 'text';
monto.name = monto.id = 'monto' + cantpagos;
monto.onblur = sumpagos;
document.getElementById('pagos').appendChild(monto);

Update:

I believe this line of code is the cause of your issue:

document.getElementById('pagos').innerHTML+="<br />";

Demo without that line: http://jsfiddle.net/A7aPA/
Demo with that line: http://jsfiddle.net/A7aPA/1/

As you can see, the first demo works, the second one doesn't.

Remove that line and it should work...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜