Hristo Hristov
Hristo Hristov

Reputation: 33

Submit Button for Right Answer?

Got stuck on something that I thought would be quite straight forward.

I am trying to create a form, where you are asked a question and you need to input the right answer and submit it. So I need to make a submit button that only works if an exact value is typed in a text field of some sort. If the answer is different, then the button should just do nothing (or make a sound or something).

Any suggestions on where to start on this would be highly appreciated!

Upvotes: 3

Views: 1536

Answers (3)

Krushil
Krushil

Reputation: 11

You would need to first of all make a function in JavaScript something like CorrectAnswer which stores the right answer and then when the user clicks on it, you would need to use on click where you’d need to use CorrectAnswer id where the script checks for the correct answer.

Upvotes: 1

NothingtoSay
NothingtoSay

Reputation: 159

As you wrote, you can disable the button if the answer is wrong. Now, you haven’t given any code. So, I am showing an example only:

We gonna use javascript for this. Let's create a form

<form method="post">
 <input type="text" id="question1" onchange="check()">
<input type="submit" id="submit">
</form>

We are running a js function everytime the user makes some change in the text.

Javascript function:

function check(){
var correctAns = 2;
var input = document.getElementById('question1').value;
var btn = document.getElementById('submit');

if(input == correctAns){
btn.disabled = "false"; 
}else{
btn.disabled = "true";
}  
}

So, you will not be able to press the button, if you provide a wrong answer. Hope this helps!

Upvotes: 0

luek baja
luek baja

Reputation: 1674

You can use something like this:

function check() {
  var correctAnswer = "4";
  var inputValue = document.getElementById("ELEMENT_ID").value;

  if(inputValue !== correcetAnswer) {
    return false;
  };
};

HTML:

<form onsubmit="return check()">

</form>

Just run a function with the onsubmit attribute and have the function return false if the answer is wrong. Use the value property of the input box to get user input.

Upvotes: 1

Related Questions