Radio buttons to toggle div in HAML

I'd like to do something very simple: reveal one div if one radio button is selected, hiding another div, and revealing that div if the other radio button is selected, thus hiding the first div.

This is what I have, which doesn't work:

          = form.radio_button "meta_data[quantity_meta][type]", value: "range", onclick: "toggleDiv('.toggle-range', '.toggle-fixed');"
          = form.label "meta_data[quantity_meta][type]", "range"
          = form.radio_button "meta_data[quantity_meta][type]", value: "fixed", onclick: "toggleDiv('.toggle-fixed', '.toggle-range');"
          = form.label "meta_data[quantity_meta][type]", "fixed"

        = form.label "YO!", hidden: true

        = form.label "Can't stop the feeling!", hidden: true

And the JavaScript (accessible via asset pipeline):

function toggleDiv(hideDiv, showDiv) {

Pretty simple. Yet when I render the page and inspect my "radio buttons", this is what I see:

<input type="radio" value="{:value=>"range", :onclick=>"toggleDiv('.toggle-range', '.toggle-fixed')"}" name="meta_data[quantity_meta][type]">

It's putting my onclick attribute into the value attribute of the radio button.

How can I accomplish my goal here?

1 answer

  • answered 2022-05-03 17:57 max

    This has nothing to do with Haml or your javascript. The signature of radio_button is:

    radio_button(method, tag_value, options = {}) 

    Since you're passing a hash as the second argument it is getting cast to a string. Instead you need:

    = form.radio_button "meta_data[quantity_meta][type]", "range", onclick: "toggleDiv('.toggle-range', '.toggle-fixed');"

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum