...

View Full Version : Dynamically generated input fields length?



bunal
09-28-2005, 08:40 AM
have a problem with getting the length of the dynamically generated input fields by the getElementbyname method. Here is my code.

I really appriciate if someone can help me on that


<script language="javascript">
var totalrecipients = 1;

function delRow(button)
{
//window.alert(button.parentNode.nodename)
var row = button.parentNode.parentNode;
var tbody = document.getElementById('recipients').getElementsByTagName('tbody')[0];
tbody.removeChild(row);
totalrecipients--;
}

function addRow()
{
var totalrecipients_name = 'toname'
var totalrecipients_email = 'toemail'

var tbody = document.getElementById('recipients').getElementsByTagName('tbody')[0];

var row = document.createElement('TR');

var cell1 = document.createElement('TD');
var inp1 = document.createElement('INPUT');
inp1.setAttribute('type','text');
inp1.setAttribute('name',totalrecipients_name);
inp1.setAttribute('value',totalrecipients_name);


var cell2 = document.createElement('TD');
var inp2 = document.createElement('INPUT');
inp2.setAttribute('type','text');
inp2.setAttribute('name',totalrecipients_email);
inp2.setAttribute('value',totalrecipients_email);

var cell3 = document.createElement('TD');
var inp3 = document.createElement('INPUT');
inp3.setAttribute('type','button');
inp3.setAttribute('value','Delete');

inp2.onclick=function(){show2(this);}
inp3.onclick=function(){delRow(this);}

cell1.appendChild(inp1);
cell2.appendChild(inp2);
cell3.appendChild(inp3);

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

tbody.appendChild(row);

totalrecipients++;
var x = document.getElementsByName("toname")
window.alert(x.length);
}
</script>

</head>

<body>
<table width="500" id="recipients">
<tbody>
<tr>
<td width="163">TO</td>
<td width="243">&nbsp;</td>
<td width="94">&nbsp;</td>
</tr>
<tr>
<td>Name</td>
<td>Email</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><input name="toname0" type="text" id="toname" value="d"></td>
<td><input name="toemail0" type="text" id="toemail" value="d"></td>
<td></td>
</tr>
</tbody>
<tr>
<td><input type="button" value="Add recipient" onClick="addRow();"></td>
<td></td>
<td>&nbsp;</td>
</tr>
</table>

glenngv
09-28-2005, 12:45 PM
It's getElementByName not getElementsByName. But getElementByName is wrongly implemented in some browsers. The safest way is to use DOM 0.


var f = document.forms[0];
var x = f.elements[totalrecipients_email];
window.alert(x.length);
I noticed that you don't have form tag. You need to add it.

bunal
09-28-2005, 01:20 PM
Thanks for the answer. I am using it on Ajax. Will have a form when completed ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum