简体   繁体   中英

Javascript random number loop not working

I have the following function that should return to me a generated number of the length I have input in the input field. Here is the example: http://jsfiddle.net/s91fb8jx/31/

As I click the button nothing is returned, why?

   $(document).ready(function(){
    var $group = "09",
        $group_l = $group.length,
        $size = $('#size').val();

    function num_gen(num){
        var output = "";

        if(size > 0){
            while(output.length < num) {
                output += $group[Math.floor(Math.random() * $group_l)];
            }
            return output;
        } else {
            return ""
        }
    }

    $('#btn').on('click', function(){
        console.log(num_gen($size));
    }); 
});

You have two errors. First, you are getting the value of your text field before it has a value. You should get this value when the button is clicked. Second, if(size > 0){ should be if(num > 0){ .

$(document).ready(function(){
    var $group = "09",
        $group_l = $group.length;

    function num_gen(num){
        var output = "";

        if(num > 0){
            while(output.length < num) {
                output += $group[Math.floor(Math.random() * $group_l)];
            }
            return output;
        } else {
            return ""
        }
    }

    $('#btn').on('click', function(){
        console.log(num_gen($('#size').val())); // get the value here
    }); 
});

Try this out

$(document).ready(function(){
  var $group = "09",
      $group_l = $group.length;

function num_gen(num){
    var output = "";

    if(num > 0){
        while(output.length < num) {
            output += $group[Math.floor(Math.random() * $group_l)];
        }
        return output;
    } else {
        return ""
    }
}

$('#btn').on('click', function(){
    console.log(num_gen($('#size').val()));
}); 

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM