0

I'm building a multiple choice quiz game and I'm trying to mimic the functionality of Duolingo, where basically you have 3 numbered multiple choice answers and a user can just type "1", "2" or "3" in order to select their preferred answer choice (see image).

How do I mimic this functionality? Using JS or whatever other tools. Currently each answer choice in my app has a hidden radio input and the user has to click on an answer with their mouse in order to select but mouses are the worst! Any help would be great! Thank you!

duolingo answer selection example

strohy1210
  • 281
  • 3
  • 10

4 Answers4

1

Use mousetrap! It captures keystrokes on a page and allows you to set up event handlers for each key. It would be an easy exercise to assign a handler for each number key needed.

m-albert
  • 1,089
  • 8
  • 15
1

If your form is an html form like this:

<form>
<input type="radio" name="gender" id="button1" value="red" checked>Red<br>
<input type="radio" name="gender" id="button2" value="blue"> Blue<br>
<input type="radio" name="gender" id="button3" value="green"> Green  
</form>

Then you just need a little bit of jquery to change which radio button is selected

$(document).keypress(function(e) {
    console.log("keypress noticed");
if(e.which == 49) {
       $("#button1").prop("checked", true)

}
    if(e.which == 50) {
        $("#button2").prop("checked", true)
}
    if(e.which == 51) {
        $("#button3").prop("checked", true)
}
});
0

guessing could, in part, listen for keyboard input and if key entered, do x

also, Simplest way to detect keypresses in javascript, in case that may be of interest

also:

$(document).on('keypress', function(e) {
  console.log(String.fromCharCode(e.keyCode));
})

in case that may be of interest

Community
  • 1
  • 1
Drew
  • 2,583
  • 5
  • 36
  • 54
  • How do I check if a user enters "1" or "2", "3" etc? For some reason I could only find info on general keypresses such as left/right/enter. – strohy1210 Feb 18 '16 at 18:51
  • response revised! also, if I had to guess, with the vanilla js technique key value would be on `keyCode` and with the jQuery approach on `which` in case that may be of interest – Drew Feb 18 '16 at 18:57
0
 $("input").on("keydown", function (event)
  {
      if (event.which == 13)
      {
          event.preventDefault();
          ..
      }
  });

the 13 is for enter not sure wich one is for 1,2,3 just console.log(event.wich)

Alex C
  • 137
  • 8