# Keystroke commands

**URL:** <https://www.ruby-forum.com/t/keystroke-commands/148008>\
**Category:** Rails\
**Created:** [September 8, 2008, 9:16am UTC](https://www.ruby-forum.com/t/keystroke-commands/148008 "2008-09-08T09:16:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![crucoba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e8c25b/32.png) [@crucoba](https://www.ruby-forum.com/u/crucoba)\
**Post date:** [September 8, 2008, 9:16am UTC](https://www.ruby-forum.com/t/keystroke-commands/148008/1 "2008-09-08T09:16:46Z")

</div>

I wanted to bind keystroke commands to actions, and the way that I was  
doing that was inelegant enough that I’m sure I’m missing something.

The actions in question are also accessible via buttons on the page;  
two of the buttons are simple:

\<%= button\_to(“Correct”, :action =\> :correct\_answer, :item =\> answer) %\>  
\<%= button\_to(“Incorrect”, :action =\> :incorrect\_answer, :item =\>  
answer) %\>

and one is more AJAXy:

\<% form\_remote\_tag :url =\> { :action =\> :answer, :item =\> ask } do %\>  
\<%= submit\_tag “Answer” %\>  
\<% end %\>

I ended up sticking in ids in HTML entities related to these buttons,  
and writing javascript code to find the button and call either  
submit() (in the simple case) or onsubmit() (in the AJAX case). But  
doing so was inelegant enough that I’m assuming that I’m missing a  
more Railsy way of doing this, that will directly generate javascript  
to call the actions in question. (I’ll include the buttons and  
javascript I’m currently using after my signature.)

Thanks for any help; as is doubtless obvious from the above, I’m new  
to Rails. (And, for that matter, to javascript.)

David C.  
removed\_email\_address@domain.invalid

\<%= button\_to(“Yes”, { :action =\> :correct\_answer, :item =\> answer },  
{ :id =\> “yes” } ) %\>  
\<%= button\_to(“No”, { :action =\> :incorrect\_answer, :item =\> answer },  
{ :id =\> “no” } ) %\>

\<% form\_remote\_tag :url =\> { :action =\> :answer, :item =\> ask },  
:html =\> { :id =\> “show-answer” } do %\>  
\<%= submit\_tag “Answer” %\>  
\<% end %\>

function locateForm(inputName) {  
input = document.getElementById(inputName);  
if (!input)  
return null;  
forms = document.getElementsByTagName(“form”);  
for (i = 0; i \< forms.length; ++i) {  
if (forms[i].childNodes[0].childNodes[0] == input)  
return forms[i];  
}  
return null;  
}

function submitForm(event) {  
if (event.keyCode == 65) {  
document.getElementById(“show-answer”).onsubmit();  
} else if (event.keyCode == 89) {  
locateForm(“yes”).submit();  
} else if(event.keyCode == 78) {  
locateForm(“no”).submit();  
}  
}

Event.observe(document, ‘keydown’, submitForm);
