0

I have a PHP/JS/MySQL driven quiz site with multiple choice questions. The answer alternatives are displayed on four buttons.

<input type = "button" value="$alt1" onClick="changeQuestion('alternative1'); this.style.backgroundColor = '#A9A9A9'">

Is there any way to, when a button has been clicked, disable onclick for all buttons until the JS function is complete? As it is now, it's possible for a user to click several alternatives to one question which of course messes up the result.

The JS function called by onclick uses AJAX to call a PHP file which processes the answer.

Many thanks

2 Answers 2

5

The easiest way to do this is to have some sort of flag value:

var pending = false;

function changeQuestion(nam)
{
    // test to see if something else set the state to pending.
    // if so... return, we don't want this to happen.
    if(pending) return;
    pending = true; // raise the flag!

    /* ... later ... */
    // in the success method of your AJAX call add:
    pending = false;
Sign up to request clarification or add additional context in comments.

1 Comment

I moved the background color change script from the button HTML and added it like this in the JS function but this seems to stop the function from running. What is wrong with it? if(pending) return; pending = true; // raise the flag! document.getElementById(answer).style.backgroundColor = "#A9A9A9";
0

Just run your Ajax synchronously.

In jQuery, you just need to add the async=false parameter:

$.ajax({
    url:'foo.handler.php',
    data:params,
    async:false,
    success:function(){
        // do something cool.
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.