Today's Posts Follow Us On Twitter! TFL Members on Twitter  
Forum search: Advanced Search  
Navigation
Marketplace
  Members Login:
Lost password?
  Forum Statistics:
Forum Members: 24,254
Total Threads: 80,792
Total Posts: 566,471
There are 600 users currently browsing (tf).
 
  Our Partners:
 
  TalkFreelance     Design and Development     Programming     Javascript :

Counting how many form elements have been selected

Thread title: Counting how many form elements have been selected
Closed Thread    
    Thread tools Search this thread Display Modes  
08-19-2008, 03:26 PM
#1
JohnK is offline JohnK
Status: Junior Member
Join date: Apr 2008
Location:
Expertise:
Software:
 
Posts: 44
iTrader: -1 / 0%
 

JohnK is on a distinguished road

  Old  Counting how many form elements have been selected

Well that's generally not so difficult and works something like this:

Code:
function countCheckboxes() {
var total = 0;
var max = form.element.length;
for (var i=0; i<max; i++) {
if (eval("document.form.element[" + i + "].checked") == true) {
    total += 1;
   }
}
alert(total + " checkboxes have been selected.");
}
... and the countCheckboxes() function is then called onclick at the submit button.

But: this only works if more than one checkbox exists in the HTML source. The "length" object returns "undefined" if there's only one checkbox! And the counting function doesn't work anymore.

Had anybody ever to deal with this problem and knows about a solution or a workaround?

08-20-2008, 02:18 AM
#2
xdoomx is offline xdoomx
Status: Member
Join date: Feb 2005
Location: Quebec, Canada
Expertise:
Software:
 
Posts: 441
iTrader: 1 / 100%
 

xdoomx is on a distinguished road

Send a message via AIM to xdoomx Send a message via MSN to xdoomx

  Old

Code:
function countCheckBoxes(){
	var checkboxes = document.getElementsByTagName("INPUT");
	var total = 0
	for(i=0;i<checkboxes.length;i++){
		if(checkboxes[i].checked) total ++;
	}
	alert(total);
}
This should work, might behave funny if there's more than one form with checkboxes or radio buttons in the page, but that can always be fixed.

08-20-2008, 07:58 AM
#3
JohnK is offline JohnK
Status: Junior Member
Join date: Apr 2008
Location:
Expertise:
Software:
 
Posts: 44
iTrader: -1 / 0%
 

JohnK is on a distinguished road

  Old

Thank you very much, this works great! I wanted to post reputation for you but this is either not possible in this forum or I am not allowed to do this because of my low number of posts. I will try again when I have more than 10 posts.

Anyway: it's strange that it doesn't work with form.element.length. This must be a bug in the Javascript language, isn't it?

Closed Thread    


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

  Posting Rules  
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump:
 
  Contains New Posts Forum Contains New Posts   Contains No New Posts Forum Contains No New Posts   A Closed Forum Forum is Closed