Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Random variable is only returning 1 character

Hey guys im trying to generate a random password using upper and lowercase keys + numbers. the code seems to work but instead of returning 20 characters its instead returning only 1. The return seems random.
The element should be replaced why the random password every time the button is clicked.

HTML

<button id = "button5" onclick = "password()">Generate password </button> 
<p4 id = "p4" > Your password will apear here </p4>
 

This is the Javascript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function password (length ) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"


var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here 
for (var i = 0; <length ; i++) {
ranpassword +=  chara.charAt(Math.floor(Math.random() *
chara.length));
return ranpassword;

}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
console.log(password(20));

}

whenver the button is clicked, one random letter is returned in console.log and i cant seem to understand why ? Can anyone tell me why?
Any help would be great . Thanks 🙂

>Solution :

You did some mistake. Try this code,

function password (length) {
    let ranpassword = "",
        chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        charalength = chara.length;

    for (var i = 0; i<length ; i++) {
        ranpassword +=  chara.charAt(Math.floor(Math.random() *
        chara.length));
    }

    document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick="password(20)">Generate password </button> 
<p4 id = "p4" > Your password will apear here </p4>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading