Karthik
Karthik

Reputation: 33

javascript onblur function not working

I can't get onblur function at second row onwards, please help me. Here is my code.

javascript

function calc()
{
var fi = document.getElementById("one");
var se = document.getElementById("two");
var th = fi.value * 59.63;
document.getElementById("three").value=th;
} 
function addRow(){ 
//var table=document.getElementById('countTable');
var tbody=document.getElementsByTagName('TBODY')[0];
var row=document.createElement('TR');
var cell1=document.createElement('TD');
var cell2=document.createElement('TD');
var cell3=document.createElement('TD');

var cell1value='';
cell1value+='One <input type="text" name="one" id="one" value="">';
var cell2value='';
cell2value+='Two <input type="text" name="two" id="two" value="">';
var cell3value='';
cell3value+='Three <input type="text" name="three" id="three" value="">';

cell1.innerHTML=cell1value;
cell2.innerHTML=cell2value;
cell3.innerHTML=cell3value;

row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);

tbody.appendChild(row);
//alert(table+' '+row+' ');
}

HTML

<table name="entry" width="100%" id="countTable">
<TBODY>
<tr>
<td>One 
<input type="text" name="one" id="one" value="" onBlur="calc();">
</td>
<td>Two
<input type="text" name="two" id="two" value="" onBlur="calc();">
</td>
<td>Three
<input type="text" name="three" id="three" value="">
</td>
</tr>
</TBODY>
</table>

<input type="button" name="add" value="Add" onClick="addRow();">

Upvotes: 1

Views: 6429

Answers (1)

David
David

Reputation: 218877

Notice the input elements in your initial row:

<input type="text" name="one" id="one" value="" onBlur="calc();">

And the input elements in your subsequent rows:

<input type="text" name="one" id="one" value="">

There's a key difference between them which prevents the subsequent rows from making use of the onBlur event. In order to respond to the event, just like in the first row, you need to actually attach a handler for that event. Something like this:

<input type="text" name="one" id="one" value="" onBlur="calc();">

Note, however, that your code has other problems. Namely:

  • You're re-using id values, so the behavior or anything using those ids (such as your calc function) will be undefined. ids need to be unique throughout the document.
  • You're re-using name values. While allowed, this could lead to unintended side-effects when you try to use the values posted by this form. Later elements may obscure the values from earlier elements.

Upvotes: 5

Related Questions