In my website I am working on making a page that will display an image, and has a form with a text input field. I want to know if there is a way to automatically submit said form when the user types in the correct answer in the text input field?
Asked
Active
Viewed 62 times
-1
-
1You can definitely do that with JavaScript without effort. Your form will have a `submit()` method. – sjahan Nov 21 '17 at 13:17
-
1_I want to know if there is a way[...]_ Yes, there is. But this is definitely unrelated to mysql, java, and in most cases php (as the submit itself is done on the client side) – Clijsters Nov 21 '17 at 13:18
-
have a look at this https://stackoverflow.com/questions/6065101/pass-value-from-html-form-to-php-without-submitting-the-form – Sean Konig Nov 21 '17 at 13:22
1 Answers
0
You can achieve this by using JavaScript and PHP json_encode as follows:
document.addEventListener("DOMContentLoaded", function() {
var inputField = document.getElementById("yourInputField");
inputField.addEventListener("input", submitFormIfCorrect);
});
function submitFormIfCorrect(event) {
var element = event.target;
var correctAnswer = <?php echo json_encode($answer) ?>;
if (element.value === correctAnswer) {
// submit form
}
}

Sync
- 3,571
- 23
- 30
-
I should have been more clear, my website is programmed in php. The answer that the user needs to imput is pulled from a mysql query and then turned into a php variable.. is there a way to automatically submit the form when that php variable is typed into the text input box? – Joshua Miller Nov 21 '17 at 20:39
-
-
Thank you, it is working, but it's not auto submitting I have to click out of the input field to submit. – Joshua Miller Nov 21 '17 at 23:25
-
My bad. I updated my answer. It should behave like you want with `inputField.addEventListener("input", submitFormIfCorrect);`. – Sync Nov 21 '17 at 23:29
-
Works absolutely flawless, thank you so much. I could not wrap my brain around how to make this function! – Joshua Miller Nov 21 '17 at 23:58
-
No problem. :) Please accept my answer to indicate the question is solved. – Sync Nov 22 '17 at 00:03
-
Absolutely, there are a lot of critics and people who would rather nitpick than help, but you have been nothing but superb in helping. Thanks again. – Joshua Miller Nov 22 '17 at 01:26