-1

Guys i am trying to get random values when click a button and made that code but when i click somehow one value repeat itself 4 times like "k0k2k4k6" , "n0n2n4n6". Why this happenning?Cos its not a coincidence. Thanks in advance! JSFIDDLE

$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
  var word = words[Math.floor(Math.random() * words.length)];
  var myLength = 8;

  function random() {
    for (var i = 0; i < myLength; i++) {
      $('#content').append(word + i++);
    }
  }

  $('#button').click(function() {
    random();
  });

});
#content {
  width: 200px;
  height: 50px;
  border: 1px solid #333;
  margin-top: 50px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click</button>
<div id="content"></div>

3 Answers3

2

Why is it generating 4 times?

Because your maximum limit is 8 and you are incrementing twice, one in the for loop and inside there.

Moving the word (generated dynamically) definition inside the loop solves it:

$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
  var myLength = 8;

  function random() {
    // Also I would clear before generating new:
    $('#content').html("");
    for (var i = 0; i < myLength; i++) {
      var word = words[Math.floor(Math.random() * words.length)];
      $('#content').append(word + i++);
    }
  }

  $('#button').click(function() {
    random();
  });

});
#content {
  width: 200px;
  height: 50px;
  border: 1px solid #333;
  margin-top: 50px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click</button>
<div id="content"></div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Move your variables into the function:

$(function() {

 function random() {
   var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
   var word = words[Math.floor(Math.random() * words.length)];
   var myLength = 8;
   for (var i = 0; i < myLength; i++) {
     $('#content').append(word + i++);
   }
 }

 $('#button').click(function() {
   random();
 });

});
Moshe Karmel
  • 459
  • 4
  • 9
0

Try this

$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
  var myLength = 8;

  function random() {
    var word = words[Math.floor(Math.random() * words.length)];

    for (var i = 0; i < myLength; i++) {
      $('#content').append(word + i++);
    }
  }

  $('#button').click(function() {
    $('#content').html('');
    random();
  });

});
Miguel Ike
  • 484
  • 1
  • 6
  • 19