Nuby: How to use onKeyPress to call JavaScript?

Hi,

I'm new to rails, so please be nice to me :slight_smile:

I'm trying to do some simple JavaScript in Rails but am having a lot of difficulty getting it to work.

Basically, I have a form with a text field. When the user types in the text field, I want to respond to each key press event and update another field on the screen.

I want to do this *without* a round-trip to the server.

In straight HTML, it would look something like this:

<head> <script>   function test(textfield) {     document.all['output'].innerHTML = textfield.value.length;   } </script> </head> <body>   <form>     <input type="text" onkeyup="test(this)"/>   </form>   <span id="output"></span> </body>

I've tried many permutations of the text_field_tag and none of them seem to work as I expect. The closest I got was

<%= text_field_tag 'answer', nil, :onkeypress => "alert('asdf')" %>

but I can't seem to get it to call my own javascript function.

i.e. this doesn't work <%= text_field_tag 'answer', nil, :onkeypress => "test(this)" %>

Is what I'm trying to do even possible?

Have you tried using another function name besides "test." Initially this confused me too, but then I thought maybe "test" is a keyword in JavaScript so I tried something else and it seems to work just fine.

Craig User wrote:

Try this function: http://api.rubyonrails.com/classes/ActionView/Helpers/PrototypeHelper.html#M001636 It "observes" a field in the form and calls a callback function, ajax functions by default.

You must include prototype library too. Use the helper <%= javascript_include_tag :defaults %>

Thank you all for your help. I was able to get this working by doing the following:

<%= observe_field 'answer', :function => "getStyle($F('answer'))", :frequency => 1 %>

and then in my application.js

function getStyle(answer) {     var styleField = document.getElementById('style');     styleField.innerHTML = answer }

In the interests of DRY though, does anyone know how to pass in a non-form variable to my javascript function so that I don't have to do the document.getElementById lookup?

i.e. getStyle($F('answer'), $P('otherElement'))

I guess I'm asking if there's a 'page' equivalent to the 'form' shorthand "$F".

Have you looked at <http://prototypejs.org/api/utility&gt; ?