vendredi 30 octobre 2015

Using .html() to clear previous random string not working

I am writing a short function that appends a random string that is equal in length to a given word. For example, if you input the word 'hello' it would return a random string that is 5 letters long.

This part works as expected. However, I am using $('output').html(""); to overwrite the last random string. I have used this for other functions before and it has worked as expected but it does not here. I have tried moving it around the function to see if it has something to do with the order of the function but it's not deleting the previous random string.

What am I doing wrong?

Fiddle here

HTML:

<input type="text" id="input">
<button id="button">Click Me</button>
<div id="output"></div>

JavaScript:

var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function () {
    $('#button').on('click', function () {

        var value = ($('#input').val());
        for (i = 0; i < value.length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        };
        $('#input').val("");
        $('#output').html("");
        $('#output').html(text);
    });
});




Aucun commentaire:

Enregistrer un commentaire