Friday, November 18, 2011

Pass Multiple Parameters into a Javascript Function











Learn about the good parts and bad parts of javascript. When java applets failed, javascript quickly became the language of the web by default. This book digs through the good and indentions and blunders to give you a detailed look at the good parts of javascript.











It includes,

  • Syntax
  • Objects
  • Functions
  • Inheritance
  • Arrays
  • Regular expressions
  • Methods
  • Style
  • Beautiful features

It has taken me years, and I finally came across the solution to passing multiple parameters into a javascript function.

Javascript functions have a special property called arguments. They contain an array of input parameters. You can simply use the length property of the array, to find out how many parameters were passed to it.

When setting up your function, do not specify and parameters. For example I have a function called bind, that I use to call generic methods. It uses two parameters, the first parameter specifies the name of the function to be called, and the second parameter specifies the page it is used on.

The function takes no arguments, and is simple specified as bind().

In the function I setup a for loop to loop through the arguments, and determine how many parameters were passed.

for (var i = 0; i < arguments.length; i++) //Loop through total number of arguments passed into the function. { var function_name = arguments[0]; //Get first parameter. //Perform case statements here. }

When you call the function, simply specify the function call as such, bind('para1', 'para2'). That's it. It's really that easy. Then, access each parameter as an array element.

This eliminates the need to store values into hidden fields. Your functions less complicated. There are many times you need to pass more than one parameter into a javascript function. You cannot setup two parameters in the function declaration. The second parameter will always end up being null.

Bookmark this blog for future reference. It will certainly come useful.

No comments:

Post a Comment

Programming for the Web