PDA

View Full Version : Validating dynamic form fields when you don't know how many there are


jim_denney
01-06-2003, 03:55 PM
I have a form created using data. I am placing a check box, a description and a cost for each record returned. When a user checks a check box, I want to update the total cost to the user. I never know how many records will be returned (1-40 is typical). I named the check boxes chk1, chk2, etc., and each corresponding text box txt1, txt2, etc.

When I try to call a function using the OnClick event, all I get is errors. Does anyone know how to determine if a check box control exists and if so, include the corresponding text box value in a total.

Any help is appreciated.

beetle
01-06-2003, 04:59 PM
Ya, let's say you have a form named "myForm" and and input named "myInput"

var f = document.myForm;
if ( f.elements['myInput'] )
{
// do something with myInput
}
else
{
// myInput doesn't exist
}

jim_denney
01-08-2003, 05:07 PM
Thanks to Beetle for supplying a starting point for this problem. I am afraid I wan't too clear in the description of the problem. For each record read in form a DB I create a chkbox (named ChkEvent#), a description of the item and a cost field (TbxCost#). I never know how many records there will be, but if records do show and the user checks an item, I want a running total to update (TbxTtlCost). This function runs through the elemnts on the form and when it finds a check box that is checked, it adds the cost amount to the total. Hope this helps others. This is the first version, I will be cleaning it up now, but it does work and should give anyone else needing simnilar functiality a good model to modify.


function updt_price()
{
var f = document.frmRegister;
var varCalcCost = 0;
var cntr = 0;
var tmp_val;
var ttlfld = "TbxTtlCost";
var fldname = "Chk"
for (var i = 0; i<f.length; i++) {
fldname = f.elements[i].name;
if ( String(fldname).substring(0,3) == "Chk")
{
cntr = String(fldname).substring(8);
tmp_val = eval("document.frmRegister.ChkEvent"+cntr+".checked");
if (tmp_val == true)
{
fldname = "document.frmRegister.TbxCost" + cntr + ".value";
tmp_val = eval("document.frmRegister.TbxCost" + cntr + ".value")
varCalcCost += tmp_val - 0;
}
}
}

document.frmRegister.TbxTtlCost.value = varCalcCost;
}