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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript - Sum mulitple form option values 2

Status
Not open for further replies.

mikesoper

Technical User
Jun 10, 2005
21
DK
Hi there,
I need a way to sum all selected <option> values from within a form. My form could have up to 100 <selects> all with a name of "Frequencynnnn" nnnn being an ID number.

I have tried to modify this script I found:

function getFields() { var inputs = document.getElementsByTagName('option'), result = 0; for( var i = 0; i < inputs.length; i++ ) { var num = parseFloat( inputs.value ); //if it's a valid number add it if( !isNaN( num ) ) result += num; } alert( result ); }

However all this will do is sum all values from all options/drop downs - what I need is just the selected values added together.

Can anyone help?

Thanks
 
Hi

Do any of your [tt]select[/tt] have [tt]multiple[/tt] attribute set ? If not, would be enough to change "input" to "select".


Feherke.
 
Don't you mean "option" to select rather than input?

In other words, as long as your dropdowns can't have more than one option selected from each of them then all you need is to get each select, and access their values.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi,

Each select can only have 1 option selected.

Thanks
 
In that case:
Code:
function getFields() { 
    var inputs = document.getElementsByTagName('[red]select[/red]');      result = 0;  
   for( var i = 0; i < inputs.length; i++ ) { 
                    var num = parseFloat( inputs[i].value );   
          //if it's a valid number add it   
          if( !isNaN( num ) ) result += num; 
             }  
     alert( result ); 
}


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Thanks both of you.

I cant beleive I didnt try that - so simple!!

Sometimes the easiest answers are the hardest to find (in my case anyway!)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top