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

Can't change an element's innerText inside a callback

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 class="..." type="button" onclick=show_confirm_button()>
    <span id="reset-button">Reset</span>
</button>

What am I missing?

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

>Solution :

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 class="..." type="button" onclick=show_confirm_button() id="reset-button">
    <span id="reset-button-text">Reset</span>
</button>
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