In this form, there is no problem when adding (when you enter some values in form fields, script adds them and writes the total in "I Alt" area). But, I want to add top 5 values. So, for example, when I enter 5,2,6,8,10,20,30 in fields, in "I alt" area it must be 74 (30+20+10+8+4).
Is there a script like this? Please help. I don't have any experience on JS and can't understand codes.
function calc(){
var theValues=new Array(parseInt(document.autoSumForm.s1c.value), // Add all values to an array
parseInt(document.autoSumForm.s1p.value),
parseInt(document.autoSumForm.s2c.value),
parseInt(document.autoSumForm.s2p.value),
parseInt(document.autoSumForm.s3c.value),
parseInt(document.autoSumForm.s3p.value),
parseInt(document.autoSumForm.s4c.value),
parseInt(document.autoSumForm.s4p.value),
parseInt(document.autoSumForm.s5p.value),
parseInt(document.autoSumForm.s5c.value),
parseInt(document.autoSumForm.s6p.value),
parseInt(document.autoSumForm.s6c.value),
parseInt()document.autoSumForm.finale.value)
theValues.sort(mySort)
document.autoSumForm.ialt.value = (theValues[0]+theValues[1]+theValues[2]+theValues[3]+theValues[4]);
}
function mySort(a,b){
return a-b
}
I think that should work, but I'm not sure if the quick way to do numerical sorting was to do a-b or b-a in mySort. But I guess you'll notice since if it's the wrong way, you'll get the five smallest values.
Also note that non-numerical values will mess up the script.
If you want to only allow numbers in a field, try this:
Code:
function Cleanup(field){
input=field.value.substring(0,20) // Set absolute max length to 20
while(/\D/.test(input)){
input=input.replace(/\D/,'')
}
while(input.substring(0,1)=="0"){
input=input.substring(1)
}
if(input==''){
input=0
}
field.value=input
}
...
<input type="text" onchange="cleanup(this)">
Umm why first put the names in a string, and then split them?
You might as well do
Code:
var inputnames = ["s1c","s1p","s2c","s2p","s3c","s3p","s4c","s4p","s5p","s5c","s6p","s6c","s7c","s7p","s8c","s8p","s9c","s9p","s10c","s10p","s11c","s11p","s12c","s12p","finale"]
I do not recommend using eval(). (search Google for "eval is evil" and you'll find out why)