Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Apr 2007
    Posts
    144
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Empty Function Parameters

    How do i declare a default value in a function? I have a simple function

    Code:
    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

    [HTML]<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=''

    Code:
    function color_input(id,token=''){}
    How do i set a default param in a JS function?

  • #2
    Regular Coder
    Join Date
    Mar 2007
    Posts
    357
    Thanks
    46
    Thanked 22 Times in 21 Posts
    Like so:

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

    On second thoughts, you could also do this:

    Code:
    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 ===.
    Last edited by flynch01; 01-28-2009 at 01:08 AM.

  • Users who have thanked flynch01 for this post:

    oesxyl (01-28-2009)

  • #3
    Regular Coder
    Join Date
    Apr 2007
    Posts
    144
    Thanks
    5
    Thanked 0 Times in 0 Posts
    @flynch01 - thanks much its perfect.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •