Home > Software engineering >  Onclick not working when I click the button
Onclick not working when I click the button

Time:12-17

Reloading the page makes the function work but not when I click the button.

    <button onclick="randomPass()">Generate passwords</button>

function randomPass() {
    let password = ""
    for (let i = 0; i < passwordLength; i  ) {
        password  = generatePass()
    }
    return password
    console.log(password)
}

const pass1 = randomPass()

firstPass.textContent = pass1

CodePudding user response:

but not when I click the button

Because the function doesn't really do anything when you click the button. The function returns a value, but the button has no way of knowing what you want done with that value.

Here you use the returned value:

const pass1 = randomPass()

firstPass.textContent = pass1

Here (in the button click) you don't:

randomPass()

If the intent is for this to all happen on a click event, put all of the logic that you want to happen into the function:

function randomPass() {
    let password = ""
    for (let i = 0; i < passwordLength; i  ) {
        password  = generatePass()
    }
    console.log(password)
    firstPass.textContent = password
}

Then whether you execute it on a click event or on the page load, it's the same operation:

randomPass()
  • Related