Red Green Repeat Adventures of a Spec Driven Junkie

TIL: How to do JavaScript onclick from Rails checkbox form

I love using rails forms to generate HTML forms for me in web pages from the server. It’s so easy:

1
2
3
4
5
 
check_box_tag('item_list[]',
              value = item.id,
              checked = false,
              { disabled: false })

But I couldn’t figure out: how to get additional JavaScript features on to them, like basic browser supported functions like onclick.

onclick="alert('hello world')"

For basic cases, building out the form manually in HTML with Ruby looping around it was enough, not pretty, but it worked.

For this one case since parts of the form was being generated dynamically and wanted onclick actions for all generated form elements, I had to find a solution.

Google and Stackoverflow kept showing me the same intro article about onclick. The Rails guides and documentation gave me a hint, which was for any extra HTML options, use:

HTML = { option: value }

but that just generated:

html="{:onclick => "value"}"

Which is very close…but not functional. Arrgh.

This was getting to me. It seems so easy but something was missing, what is it?!

So, I went into the Ruby on Rails link slack room and asked:

“What am I missing from generating ‘onclick’ working in Rails forms? I just want some front end magic from my backend forms! This is what I have tried so far: HTML = { option: value }.

A member on the slack room, Arup, replied immediately:

“Have you tried: onclick: "alert('hello world')"?”

My initial reaction was: “Of course I have! It’s so obvious”.

I took a moment to think, maybe I haven’t tried it… I tried Arup’s suggestion and yup, it worked!

Another member, Dees, confirmed it for me. He also explained that not all the forms accept HTML options the same. It’s better to check the source implementation for the differences.

More complete listing (in case I ever forget!)

1
2
3
4
5
checkbox_tag('item_list[]',
             value = item.id,
             checked = false,
             { disabled: false,
               onclick: "alert('hello world')" })

Thanks Arup & Dees!