oTree Forum >

How to Conditionally Disable the Submit Button

#1 by WD95

Hi all,

I am exploring a method to control the enablement state of the submit button, with the following scenario in mind: participants are required to answer a question, and if their answer is incorrect, the submit button will be disabled for 10 seconds. 

My initial intention was to use JavaScript to control the button's disabled state based on whether the user answered correctly. However, I encountered a challenge: the logic to determine if the user's answer is correct is executed after the form submission, which made my attempt unsuccessful.

I am wondering if there is a correct setup method or if there are other technical means to properly disable the submit button when the user answers incorrectly. Do you have any thoughts on this? Thanks in advance!

Here is the current code.
<script>
document.addEventListener('DOMContentLoaded', function() {
    var form = document.querySelector('form');

    form.addEventListener('submit', function(e) {
        if (!{{ player.is_answer_correct }}) {
            e.preventDefault(); 
            disableSubmitButtonForSeconds(10);
        }
    });

    function disableSubmitButtonForSeconds(seconds) {
        var submitButton = document.querySelector("button[type='submit']");
        submitButton.disabled = true;
        setTimeout(function() {
            submitButton.disabled = false;
        }, seconds * 1000);
    }
});
</script>

Write a reply

Set forum username