...

View Full Version : Empty Function Parameters



cesarcesar
01-27-2009, 11:59 PM
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 = '';
}

}


Called in HTML like


<input type="text" id="example_name" onblur="color_input('example_name');">

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=''){}

How do i set a default param in a JS function?

flynch01
01-28-2009, 12:03 AM
Like so:



function color_input(id,token){
if( token == null )
token = defaultvalue;
}

Edit:

On second thoughts, you could also do this:


token = token || defaultvalue

I think that could go wrong though if you for example tried to use 0. It's better to stick with the first example and use a type checking comparison with ===.

cesarcesar
01-28-2009, 12:33 PM
@flynch01 - thanks much its perfect.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum