0

I'm using Bootstrap's radio input, and want to be able to set the checked state of a set of radio conditionally, using embedded ruby, based on some instance variable value.

I want to be able to do the following:

<input type="radio" name="type" id="all" value="all" checked="<%= 'true' if @instance_variable %>">

However, if the checked attribute is included in the input tag, the radio input is checked, regardless of the content of the attribute, even if I set checked to be false.

I would like to avoid using jQuery to achieve this.

Is there a way to achieve what I'm trying to do with embedded ruby?

1 Answers1

0

You might want to use blank? to check the variable in this case. And display checked only when you want it selected.

<input type="radio" name="type" id="all" value="all" "<%= 'checked' unless @instance_variable.blank? %>" />
Mike Gorski
  • 1,228
  • 1
  • 8
  • 13
  • Hey Mike, thanks for your reply. The problem I'm having is that, regardless of the content of the checked attribute, if the check attribute is present, that radio input is checked. I could set checked to be false, as such: `checked='false'`, but this still results in the radio input being checked – Marcus Christiansen Sep 05 '18 at 18:13
  • Ohh - I missed that. You then need to hide the `checked` attribute completely. – Mike Gorski Sep 05 '18 at 20:00
  • Yeah, exactly. I want to conditionally include the checked attribute using embedded ruby. Do you know how I can do that? – Marcus Christiansen Sep 05 '18 at 20:01
  • Hey Mike, this didn't work. The attribute is being added as a string rather than purely an attribute, so bootstrap isn't recognizing it – Marcus Christiansen Sep 05 '18 at 20:33
  • You may need to add the `active` class to the surrounding label. See this answer: https://stackoverflow.com/a/19550889/511203 – Mike Gorski Sep 06 '18 at 16:20