Asim Das
Asim Das

Reputation: 93

Javascript function with large number of arguments

I need to call a javascript function with many arguments. Is there any way to do the same as the below code but without writing each of av1, av2,...av58?

A for loop varying from 1 to 58 may do the job. But how is the syntax while defining the function?

<html>
<head>
<script>
function gft1(ff1, ff2, av1,av2, av3, av4, av5, av6, av7, av8,  av9,  av10,  av11,  av12,  av13,  av14,  av15,  av16,  av17,    av18,  av19,  av20,  av21,  av22,  av23,  av24,  av25,  av26,  av27,  av28,   av29,  av30,  av31,  av32,  av33,  av34,  av35,  av36,  av37,  av38,  av39,   av40,  av41,  av42,  av43,  av44,  av45,  av46,  av47,  av48,  av49,  av50,   av51,  av52,  av53,  av54,  av55,  av56,  av57,  av58)
{   
var uu=0;

    for ( y=1; y<=58;++ y)
        {
         uu = uu-(-document.getElementById('av'+y).value);
        }

document.getElementById(ff1).value=uu;
document.getElementById(ff2).value=uu;

}
var args = ['ff1','ff2'];
for (var i = 1; i <= 58; i++)
args.push("av" + i);
</script>  

</head>
 ....................................
   <html><input type="text" size="1" autocomplete="off"  onfocus="this.select()" name="<?php echo "av[$no]"?>" id="<?php echo "av{$no}" ? >" onkeyup="gft1.apply(null, args);"></html>

Upvotes: 0

Views: 85

Answers (2)

brk
brk

Reputation: 50316

Not sure if you at all require to pass av1,av2,av3.... when it can be simple done by passing av. Also you are not doing anything av1,av2,av3,... , you are just dealing with av & looping from 1 to 58 and appending y value to av to get the content from DOM.

So a function like this wont be sufficient?

function gft1('ff1',ff2,'av'){
var uu=0;
   for ( y=1; y<=58;++ y){
         uu = uu-(-document.getElementById('av'+y).value);
                                            // ^^ y's value will vary which will query for `av1,av2,av3..`
        }

document.getElementById(ff1).value=uu;
document.getElementById(ff2).value=uu;

}

Upvotes: 0

user3896501
user3896501

Reputation: 3037

you can use for loop to filling the arguments pool

then use apply to call it and passing the arguments

function gft1(){
    console.log(arguments);
}

var args = ['ff1','ff2'];
for (var i = 1; i <= 58; i++)
    args.push("av" + i);

gft1.apply(null, args);

see usage of apply here

Upvotes: 7

Related Questions