submit form based on number key press

158 views
Skip to first unread message

Juanfran

unread,
Jun 28, 2021, 10:08:22 AM6/28/21
to oTree help & discussion
Hello all,

I am trying to develop an attention check where people must do something to continue with the study (and the rest will be shifted to an ending page from where they cannot continue since there is no next button).

I managed to do it by adding a hidden button that they must click (instead of the ending "Next" button), so if they click Next, they are out of the study and directed to a  "check failed" page, but clicking the hidden button, they can go to the following page.

I would like to know if this can be done without clicks: to continue with the experiment, participants must press one specific key of their keyboard (for example, the number 1) instead of the next button. Then pressing this key will submit the page (like submitting a form), going to the following page of the experiment, whereas pressing Next they go to the "check failed" page.

Thank you beforehand.

Best,

Juanfran

Max R. P. Grossmann

unread,
Jun 28, 2021, 10:21:19 AM6/28/21
to Juanfran, oTree help & discussion
Hi Juanfran,

You could create a hidden form field "check". Instead of using the normal form field embedding, you could have a <input> with type="hidden" and value="0" and id="check" and name="check".

Then, include some JavaScript like this:

window.onkeypress = function (e) {
if (e.charCode == 51) {
document.getElementById("check").value = 1;
document.forms[0].submit();
}
}

(charCode 51 is the number "3")

Then, when validating fields, check whether the form field has value 0, in which case "Next" was clicked. However, if it has value 1, then the above JavaScript was triggered because number 3 was entered.

Best,

Max

Juanfran

unread,
Jun 29, 2021, 6:25:59 AM6/29/21
to oTree help & discussion
Thank you very much, Max!

I also found the way to do it yesterday night (too late to be posting it) which is almost identical. I post it below in case anyone is also interested.
Add this to the HTML code
<script>
document.addEventListener("keypress", function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '49') {
document.getElementById("attentioncheck").setAttribute("value", "1");
document.forms[0].submit();
}
});
</script>

And then, as Max explained, add an input (in my case the ID used was attentioncheck).

Honestly, I don't know the difference between using document.addEventListener and window.onkeypress, if anybody knows it would be good to learn.

Best,

Juanfran

Reply all
Reply to author
Forward
0 new messages