Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to make a conditional Radio Button checked?

Tags:

Given a radio button like so:

<%= radio_button_tag 'permission[role_id]', '2' %> 

How can I make the radio buttons checked status condition. To only be checked if @permission.role_id.nil? or if @permission.role_id == 2?

I tried:

<%= radio_button_tag 'permission[role_id]', '2', @permission.role_id.nil? ? {:checked => true} : {:checked => false} %> 

Thanks

like image 858
AnApprentice Avatar asked Jan 16 '11 23:01

AnApprentice


People also ask

How do I make radio buttons pre checked?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

How can I check if a radio button is selected?

To find the selected radio button, you follow these steps: Select all radio buttons by using a DOM method such as querySelectorAll() method. Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.

How can I set only one radio button checked?

Radio buttons are normally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time. Note: The radio group must have share the same name (the value of the name attribute) to be treated as a group.

How do you check whether a Radiobutton is checked or not in C?

Use document. getElementById('id'). checked method to check whether the element with selected id is check or not. If it is checked then display its corresponding result otherwise check the next statement.


1 Answers

The documentation for radio_button_tag says that checked isn't an options hash parameter, it's just a normal one:

radio_button_tag(name, value, checked = false, options = {}) 

So, you need to do this:

<%= radio_button_tag 'permission[role_id]', '2', !!(@permission.role_id.nil? || @permission.role_id == 2) %> 
like image 52
Skilldrick Avatar answered Sep 19 '22 16:09

Skilldrick