Sandeep Rao
Sandeep Rao

Reputation: 1757

Disable a drop down list based on the selection of above drop down list in rails

Currently I'm having a two drop down list one indicating the role and other assigning to filed. My code is

<div class="field">
    <% f.label :role %>
    <%= f.select :role, options_for_select(%w(Investigator Manager Director)) %>
</div>
<div class="field">
    <h4>Assigning to</h4>
    <%= f.collection_select( :assigned_to, User.find_all_by_role("Manager"), :id, :email)  %>
</div>

I want the second drop down list to be appeared only when an investigator is selected in the first drop down list. Any suggestions on how I can achieve this

Upvotes: 1

Views: 1814

Answers (2)

Jao
Jao

Reputation: 11

i was in a similar situation recently, though im sure your problem has been solved already, i think this will still help to others whom might be seeking answers to the same.

$(document).ready(function () {
    prevOrigin = "";
    prevDestination = "";
    $('#origin').change(function() {
        var selected = $(":selected",this).text();
        $('#destination option:contains("' + prevOrigin +'")').removeAttr("disabled");
        $('#destination option:contains("' + selected +'")').attr("disabled","disabled");
        prevOrigin = selected;
    });

    $('#destination').change(function() {
        var selected = $(":selected",this).text();
        $('#origin option:contains("' + prevDestination +'")').removeAttr("disabled");
        $('#origin option:contains("' + selected +'")').attr("disabled","disabled");
        prevDestination = selected;
    });
});​

see demo

Upvotes: 1

Justin Herrick
Justin Herrick

Reputation: 3011

You are going to want to use jquery and javascript to accomplish this. Another great resource would be this railscast by ryan bates about the exact issue.

What you basically want to do is have some javascript that is observing the current value of the :role drop down box. Normally you would do the check through a .bind (.on) to the change event of the drop down. Then you want to show/hide the :assigned_to box depending on that value. Since this appears to be a stack set of options, it should be a pretty simple bit of javascript.

jQuery ->
  ($ 'select#assigned_to').hide()
  ($ 'select#role').change ->
    role = ($ 'select#role :selected').text()
    if role is 'Investigator'
      ($ 'select#assigned_to').show()

Now obviously that was coffeescript and should be converted accordingly, but that should help you figure out what needs to be done.

Upvotes: 2

Related Questions