meritonch
meritonch

Reputation: 43

Using jQuery on rails app to hide and show (or disable enable) Select Fields

Basically i want the user to only select one of these fields, so either or, not both under any circumstances.

How can i write the Jquery code so that, if any of them is changed from their default value, the other field is either hidden or disabled?

Thanks

Here are my two select fields:

<div class="control-group" id="sel1">
  <%= f.label "Assigne", :class => 'control-label' %>
  <div class="controls" id="sel1">
    <%= f.select(:user_id,  [['Team', 0]] + User.all.collect { |p| [p.email, p.id]}, :id => 'sel1') %>
  </div>
</div>
<div class="control-group">
  <%= f.label "Team", :class => 'control-label' %>
  <div class="controls">
    <%= f.select(:team_id,  [['Department', 0]] + Team.all.collect { |p| [p.name, p.id]}, :id => 'sel2') %>
  </div>
</div>

EDIT:

I was able to write this myself:

<script>
  $(function(){
    $('#sel1').on('change',
    function(){
     if ($('#sel1').has('option').length > 5)
      {
        $('#sel2').hide();
      }
     else
      {
        $('#sel2').show();
      }
    })
  });
</script>

But its not working, it only works like this:

<script>
  $(function(){
    $('#sel1').on('change',
    function(){
        $('#sel2').hide();
    })
  });
</script>

But on this I don't show it again, if the field is revered back to none.

Any thoughts?

Upvotes: 0

Views: 957

Answers (2)

NilColor
NilColor

Reputation: 3542

You need something like this:

$('#sel1').on('change',
    function(){
     if ($('#sel1').find('option:selected').val() !== "")
      {
        $('#sel2').hide();
      }
     else
      {
        $('#sel2').show();
      }
    });

and this is html source:

<body>
<select id="sel1">
  <option val=""></option>
  <option val=0>0</option>
  <option val=1>1</option>
</select>

<select id="sel2">
  <option val=""></option>
  <option val=0>0</option>
  <option val=1>1</option>
</select>

</body>

Here you can watch this in action: http://jsbin.com/bigasitibe/2/edit

Upvotes: 1

evanbikes
evanbikes

Reputation: 4171

This assumes you don't have any other selects on the page. If you do, maybe add a class like mutually-exclusive-select or something to a parent div.

$ ->
  $selects = $('select') # or something more specific
  $selects.on 'change', ->
    $el = $(@)
    if $el.val().length
      $selects.not('#' + $el.attr('id')).attr('disabled', 'disabled')
    else 
      $selects.removeAttr('disabled')

Upvotes: 0

Related Questions