Paulo Paulo - 2 months ago 7
Javascript Question

How to make a field To appears only if an option is select, using Rails and JavaScript?

Sorry for my bad english.

I am writing a WebApp using Ruby on Railland and I need a field to be show up only if option is selected.

Here is my form in question:

app/views/gastos/_form.html.erb

<div class="field" id="ddlSelect">
<%= f.label "Tipo de Pagamento" %><br>
<%= f.select(:payment_type, options_for_select([['À vista', 1], ['À prazo', 2], ['Misto', 3]]), { include_blank: true }) %>

<input type="text" id="hdnPro" value="product" style='display:none'/>
</div>


app/assets/javascripts/gastos.js

var ddlSelect;

ddlSelect = function() {
$('#ddlSelect').('change',function(){
if($(this).val() == 'À prazo' || 'Misto'){
$('#hdnPro').show();
}else{
$('#hdnPro').hide();
}
});

}

$(document).ready(function() {
ddlSelect();
})


Two others questions: how to re-write this line to embedded ruby

<input type="text" id="hdnPro" value="product" style='display:none'/>


And how to connect the _form to gastos.js.

Thanks

Answer

This is how I fixed my code.

<div>
              <div class="field">
                <%= f.label "Forma de Pagamento" %><br>
                <%= f.select :forma_pagamento, forma_de_pagamento, { include_blank: true }, { :id => "forma_pagamento"} %>
              </div>
              <script >
                $('#forma_pagamento').on('change',function(){
                  if($(this).val() == 1){
                        $('#avista').show();
                        $('#aprazo').hide();
                        $('#parcelas').hide();

                  }if($(this).val() == 2){
                        $('#avista').hide();
                        $('#aprazo').show();
                        $('#parcelas').show();

                  }if($(this).val() == 3){
                        $('#avista').show();
                        $('#aprazo').show();
                        $('#parcelas').show();
                  }
                });
              </script>