How do i declare a default value in a function? I have a simple function function color_input(id,token){ if (!empty(token)){ document.getElementById(id).style.backgroundColor = '#2A2A2A'; document.getElementById(id).style.color = '#DDC58C'; }else{ document.getElementById(id).style.backgroundColor = ''; document.getElementById(id).style.color = ''; } } Code (markup): Called in HTML like <input type="text" id="example_name" onblur="color_input('example_name');"> HTML: You will notice that the #2 parameter is missing in the html call. Sometimes i don't have it to send. in PHP i would just set the functions second param like token='' function color_input(id,token=''){} Code (markup): How do i set a default param in a JS function?
Hi, you can either use function color_input(id){ ... and then check for #2 parameter as if(!empty(arguments[1])) ... } or you can keep it as you have it - function color_input(id,token){} and when you call this function you always fill the token value - null, or '' if not needed - <input type="text" id="example_name" onblur="color_input('example_name',null);">
You cannot assign default values to javascript functions. This is very annoying, but the easiest solution is quite simple. Assuming you have a function that has two parameters, but you call it with just one (just like you did in your code), but you want to have a default value for the parameters, you can do something like this: function test(param1, param2) { if(!param1) param1 = 'default'; //or if(param2 == 'undefined') param2 = 1; } Code (markup): Then, if you call the function with just one parameter - param2 will have the value of 1. If you call it without parameters, param1 will be 'default' and param2 will be 1... If a parameter is not set when you call the function, the variable exists within the function scope, but is 'undefined'.
@lp1501 - thanks for your suggestion. This will be easier though to add this to my function. if (typeof token != 'undefined') Code (markup):
yep, this is another way to check if the parameter is not set. Javascript variables and types are veeery weird, thus all three methods work for checking if a parameter is passed or not
what i tend to do is use json and merge options... for instance: // in mootools, you can use $merge... var foobar = function(options) { var options = $merge({ "token": "2", "margin": "150px", "title": "My title" }, options); console.log(options.title, options.margin); // will output 'new title' and '150px' console.log(options); // will output the whole object complete with token's default as well }; foobar({ title: "new title" }); // or run as default values only... foobar(); PHP: the advantages are that you can add as many params as you need to via the function call, you don't need to pre-define them in the function definition or anything like that, no relying on the arguments' order - each option has a name space you can find easily.