Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Form collection with one object - loop fails 1

Status
Not open for further replies.

travisbrown

Technical User
Dec 31, 2001
1,016
I'm trying to loop through a series of checkboxes, but can't get the loop to fire if there is only one checkbox in the collection. Works fine if there is more than one, but the length when there is only one returns undefined. I'm sure it's something obvious, but I don't get it.

See anything?

Code:
	var cbCollection = document.forms[0].elements['payment'];
	var checkboxarray;
	var payout = 0;
	var invoices = "";
	var counter = 0;
	for ( var i = 0; i <= cbCollection.length; i++ ) {
		if ( cbCollection[i].checked )  {
			payout = payout + (document.getElementById('amount_' + i).value*1);
			if ( counter == 0 ) 
				{invoices = cbCollection[i].value;}
			else 
				invoices = invoices + ',' + cbCollection[i].value
				counter = counter + 1;
		}
	}
 
Hmm...Firefox tells me cbCollection has no properties when I use getElementsByName.

var cbCollection = document.getElementsByName['payment'];
alert(cbCollection.length);
 
oops. () instead of []

But, I'm still stymied.

Error: cbCollection has no properties at this line: cbCollection.checked

Code:
<input checked="checked" name="payment" value="227" onclick="getPayoutTotal();" type="checkbox">

Code:
	var cbCollection = document.getElementsByName('payment');
	var checkboxarray;
	var payout = 0;
	var invoices = "";
	var counter = 0;
	for ( var i = 0; i <= cbCollection.length; i++ ) {
		if ( cbCollection[i].checked == true )  {
			payout = payout + (document.getElementById('amount_' + i).value*1);
			if ( counter == 0 ) 
				{invoices = cbCollection[i].value;}
			else 
				invoices = invoices + ',' + cbCollection[i].value
				counter = counter + 1;
		}
	}
	payout = payout/100
	document.getElementById('payment_total').innerHTML = '$' + Math.round(payout*100)/100
	document.getElementById('pay_commission').value = Math.round(payout*100)/100;
	document.getElementById('pay_total').value = Math.round(payout*1000)/100;
	document.getElementById('pay_invoices').value = invoices;
 
Ah. Figured it out. <= should be <. <= runs an extra loop out of the range of the collection.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top