I want to create a very simple form, which one question per page and I would like the user to be able to choose an option by pressing a number key. The question will be:
How useful did you find the service? Use the number keys to select an option.
Very good
Good
Ok
Poor
Very poor
Thus if they hit ‘3’ they would be selecting ‘Ok’. Is this possible?
Just to clarify, when you say “by pressing a number key”:
Do you want a user to press a key and the form gets automatically submitted?
Or, do you want the user to type a number into an input field, then press a submit button (or return) to submit the form?
Ha ha - sorry, the first! I want them to hit 3 if they want option 3, which would then highlight that option (I might put a tick next to it) and then move on to the next option.
Hi Del,
As I mentioned, that’s a bit trickier.
My first idea would be to use a form and the onkeypress event to have it submit.
I’m not sure this is the best way to go though. Maybe someone else has an idea?
Anyways, I’m off to work now. If their are no replies by the time I get back, I’ll see what I can come up with.
as Pullo said, use the keypress or keyup action (I’ve always used the keyup event. Don’t ask me why though :)) to select the “ok” option (if it’s a div, then set a hidden field) and then call upon the submit function of the form.
Then the following JavaScript will do exactly what you want
$(document).ready(function(){
$("body").on("keyup", function(e) {
var charCode = e.keyCode,
key,
$choices = $("#choices");
if ( (charCode >= 49 && charCode <= 53) || (charCode >= 97 && charCode <= 101) ) {
if (charCode > 96) {
charCode = charCode - 48; //compensate for numpad offset
}
key = String.fromCharCode(charCode);
//set the right item to checked
$("input[value="+key+"]", $choices).attr("checked", "checked");
//submit the form
$choices.closest("form").submit();
}
});
});
Basically, monitors the keyup event on the body, when it is either # 1 - 5 on the std numbers or 1 - 5 on the numpad it will process and convert the keyCode to a character (which will end up being one of 1-5), then it will find the radio button with that value and set it to checked. And of course finally, submit the form.
(Oh and don’t forget to include jQuery of course ;))