Question

I'm trying to pass a variable to a function but it isn't working.

Clicking on the DIV #getNum calls a function

<div id="getNum">GET NUM</div> 

... calling function makeID() and passing the number 17

    $(document).ready(function(){
    $("#getNum").click(function(){
        makeid(17);
        });
   });

very simple example below to show what's wanted.

function makeid(num){ // It doesn't work as the parameter isn't passed 
   var chooseLetters = "abcdefghijklmnopqrstuvwxyz";
   var loopNum=num;
  for( var i=0; i < loopNum; i++ )  // loopNum does not work!
        text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));
      return text;

} // END function makeid();

/* working example */

function makeid(num){ // why can I not pass the parameter to the for loop?
//console.log(num); // console.log reads num!
var num = num; // variable num is not read!
    var loopNum = num; // works if hard coded


        var chooseLetters = "abcdefghijklmnopqrstuvwxyz";

        for( var i=0; i < loopNum; i++ )
            text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));

        //console.log(text);
        return text;

    } // END function makeid();
Was it helpful?

Solution

the problem is your text variable. you have to define it before concatenate with it. Basically you are trying to concatenate a string to a variable that does not exists. This will throw an error and your script won't work.

text+='some text'; is shorthand for text=text+'some text'; You notice that this will give problems when the text variable is not defined in your code.

function makeid(num){ // It doesn't work as the parameter isn't passed 
text='';
   var chooseLetters = "abcdefghijklmnopqrstuvwxyz";
   var loopNum=num;
  for( var i=0; i < loopNum; i++ )  // loopNum does not work!
        text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));
      return text;

} // END function makeid();

working fiddle

http://jsfiddle.net/kasperfish/zRGCR/1/

OTHER TIPS

I believe once you say

var num = num; 

The "var num" would be a new variable which hides the original parm. Try taking this line out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top