How to disable specific value in dropdown select with simple_form?
Asked Answered
O

3

6

I am using simple_form in my rails application. I want to disable a particular value in drop-down.

Here is part of the code

= simple_form_for(@organization,url: admin_organization_path) do |f| 
 = f.input :hospital_name, input_html: { class: "form-control"}
 = f.input :parent, collection: @organizations, input_html: { class: "form-control", id: "chosen-select-speciality"}  

I tried using :disabled => @organizations.first but i was failed. Is there any other method to use.Kindly help me. thanks.

Osage answered 3/2, 2016 at 12:26 Comment(1)
Hi, Are you using chosen-rails?Roundtree
E
7

Simpleform builder for select box uses value of the each option to compare with value of disabled attribute, so you just simple have to use id of the organization to disable desired option:

= simple_form_for(@organization,url: admin_organization_path) do |f| 
 = f.input :hospital_name, input_html: { class: "form-control"}
 = f.input :parent, collection: @organizations, input_html: { class: "form-control", id: "chosen-select-speciality"}, disabled: @organizations.first.id

If you want to disable several options for selectbox, you can manually build options list inline or using helper and use it as attribute for input:

= f.input :parent,  collection: @organizations.map{|o| [o.id, o.name, {disabled: o.id.in?([1,21,10])}]}, input_html: { class: "form-control", id: "chosen-select-speciality"}
Erine answered 3/2, 2016 at 12:57 Comment(1)
it works but how do i disable multiple organizations.Osage
B
3

By using JavaScript you can easily disable a particular value in drop-down as:

$(/* option selector */).prop('disabled', true);

See it in action

Bellhop answered 3/2, 2016 at 12:56 Comment(0)
A
0

To disable the particular value use below code:

<%= f.input :parent,
collection: @organizations,
input_html: { class: "form-control",
              id: "chosen-select-speciality"},
disabled: @organizations.first.id %>

If you want to disable multiple options, put below code to fetch the list of unused organizations in your helper file:

@unused_org_list = Organization.where("Condition to fetch unused organizations")

Then, in your view file:

<%= f.input :parent,
collection: @organizations,
input_html: { class: "form-control",
              id: "chosen-select-speciality"},
disabled: @unused_org_list&.map {|u| u.id} %>

NOTE: Make sure to pass ids into disabled option as it expect id or [array of ids]

Acoustic answered 13/11, 2022 at 20:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.