Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    });
});
like image 449
adin Avatar asked Mar 23 '26 04:03

adin


2 Answers

The problem is not with the .html() part. The problem is that your var text is never getting reset.

For reference - http://jsfiddle.net/oo5eLbpu/2/

Updated answer will be as follows

var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function() {
    $('#button').on('click', function() {
        var text = ""; // moved the variable inside the click handler
        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);  
    });
});

Additionally, you can remove the following line from code

$('#output').html("");

As the line beneath it sets the content of the element.

For reference - http://jsfiddle.net/oo5eLbpu/4/

For documentation - http://api.jquery.com/html/

like image 194
Nikhil Aggarwal Avatar answered Mar 25 '26 17:03

Nikhil Aggarwal


You need also reset variable text,

$('#button').on('click', function() {
   text = '';
   // your code 
});

Example

or move text variable from parent scope to onlick handler

$('#button').on('click', function() {
   var text = '';
   // your code 
});

Example

Also you don't need

$('#output').html("");

because you set content

$('#output').html(text);
like image 45
Oleksandr T. Avatar answered Mar 25 '26 19:03

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!