Home > Enterprise >  Can't change an element's innerText inside a callback
Can't change an element's innerText inside a callback

Time:02-05

I'm trying to build a dynamic "reset" button which changes its innerText twice, in a loop: once when first clicked (changing from "Reset" to "Are you sure?") and once when clicked again (changing from "Are you sure?" to "Reset"). However, I can't get to modify the innerText inside the callback. It seems like I can modify the innerText just fine from the DOM console, so I assume that there's something that I don't know yet in terms of how event callbacks work in JS, and I can't figure out what it is.

function show_confirm_button() {
    document.getElementById('reset-button').innerText = "Are you sure?";
    document.getElementById('reset-button').onclick = reset_button;
}


function reset_button() {
    /* resetting things here */
    
    document.getElementById('reset-button').innerText = "Reset";
    document.getElementById('reset-button').onclick = show_confirm_button;
}

show_confirm_button() is used in a simple bootstrap button:

<button  type="button" onclick=show_confirm_button()>
    <span id="reset-button">Reset</span>
</button>

What am I missing?

CodePudding user response:

As @Barmar said:

You should be changing the onclick of the button, NOT the span.

This should work:

function show_confirm_button() {
    document.getElementById('reset-button-text').innerText = "Are you sure?";
    document.getElementById('reset-button').onclick = reset_button;
}


function reset_button() {
    /* resetting things here */
    
    document.getElementById('reset-button-text').innerText = "Reset";
    document.getElementById('reset-button').onclick = show_confirm_button;
}
<button  type="button" onclick=show_confirm_button() id="reset-button">
    <span id="reset-button-text">Reset</span>
</button>

  •  Tags:  
  • Related