Home > front end >  Radio buttons to toggle div in HAML
Radio buttons to toggle div in HAML

Time:05-04

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:

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

      .div.toggle-range
        = form.label "YO!", hidden: true

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

And the JavaScript (accessible via asset pipeline):

function toggleDiv(hideDiv, showDiv) {
  $(hideDiv).hide();
  $(showDiv).show();
}

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?

CodePudding user response:

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');"
  • Related