SuBzer0
SuBzer0

Reputation: 45

jQuery change event not working on Rails App

The change event of jQuery is not working on my rails application. I have a select and i want that the inputs hide or show according to the value of my select. So i have the inputs:

<div class="form-group">
    <%= f.label :tipopessoa, "Tipo de Pessoa:", class: "col-sm-2 control-label" %>
    <div class="col-sm-6">
      <%= f.select :tipopessoa, ['Jurídica', 'Física'], class: "form-control" %>
    </div>
  </div>
  <div class="form-group juridica">
    <%= f.label :cnpj, "CNPJ:", class: "col-sm-2 control-label" %>
    <div class="col-sm-6">
    <%= f.text_field :cnpj, class: "form-control" %>
  </div>
  </div>
  <div class="form-group fisica">
    <%= f.label :cpf, "CPF:", class: "col-sm-2 control-label " %>
    <div class="col-sm-6">
      <%= f.text_field :cpf, class: "form-control" %>
    </div>
  </div>
  <div class="form-group juridica">
    <%= f.label :razaosocial, "Razão Social:",class: "col-sm-2 control-label" %>
    <div class="col-sm-6">
    <%= f.text_field :razaosocial, class: "form-control" %>
  </div>
   </div>

And have the jQuery code:

<script>
jQuery(function(){
  $(document).change(function(){
     if($('#cliente_pessoatipopessoa').val() == 'Jurídica') {
              $(".juridica").show();
              $(".fisica").hide();
          } else {
              $(".fisica").show();
              $(".juridica").hide();
          }
             });
});
</script>

So when i change the select to Física, the divs that have the class "Juridica" disappear but any other changes don't work anymore.
How can I solve this?

Upvotes: 1

Views: 848

Answers (1)

Derek Story
Derek Story

Reputation: 9593

The change even should be bound to the select that is changed.

JS Fiddle

$('select').change(function() { // Bind to the select
  if ($(this).val() == 'Jurídica') { // use $(this).val() to get the changed selects value
    $(".juridica").show();
    $(".fisica").hide();
  } else {
    $(".fisica").show();
    $(".juridica").hide();
  }
});

And you can reduce your code by doing the following:

$('select').change(function(){ 
  var isEqual = $(this).val() == 'Jurídica';
  $(".juridica").toggle(isEqual); // Show if equal/ hide if not
  $(".fisica").toggle(!isEqual);  // Hide if equal/ show if not
});

JS Fiddle

Upvotes: 3

Related Questions