frenciaj
frenciaj

Reputation: 128

Materialize select dropdown not passing value to controller in Ruby

I have the following code in my view:

<div class="input-field col s6">
  <form method="POST" action="/results">
    <input type="text" id="track" class="validate" name="inicio">
    <label class="active" for="track">Nro Inicial de Tracking:</label>

</div>
  <div class="input-field col s6">
    <select name="sucu">
      <option value="" disabled selected></option>
      <option value="5472">Clorinda</option>
      <option value="5266">Formosa</option>
    </select>
    <label>Seleccionar Sucursal</label>
  </div>
  <button style="text-align:center;"class="btn waves-effect waves-light" type="submit" name="action">Submit
    <i class="material-icons right">send</i>
  </button>
</form>

And in my controller I'm grabbing the tracking number and sucu value like this:

inicio = params[:inicio].to_i
@sucursal = params[:sucu].to_i

Now, for some reason, the controller is getting the inicio param, which is a number I input, but is not getting the value of the dropdown, instead of getting one of the two values 5266 or 5472, I receive a 0.

Any idea why?

Upvotes: 0

Views: 1590

Answers (1)

Gerry
Gerry

Reputation: 10507

You are right, the error is with Materialize, which seems to ignore the select value. So, in order to get the value, you could add a hidden input that will act as a placeholder for the value that is selected, and then update its value when your select box changes.

<form method="POST" action="/results">
 <div class="input-field col s6">
    <input type="text" id="track" class="validate" name="inicio">
    <label class="active" for="track">Nro Inicial de Tracking:</label>
  </div>
  <div class="input-field col s6">
    <label>Seleccionar Sucursal</label>
    <select id="sucu_select">
      <option value="" disabled selected></option>
      <option value="5472">Clorinda</option>
      <option value="5266">Formosa</option>
    </select>
    <input type="hidden" name="sucu" id="sucu" />
  </div>
  <button style="text-align:center;"class="btn waves-effect waves-light" type="submit" name="action">Submit
    <i class="material-icons right">send</i>
  </button>
</form>

<script type="text/javascript">
$(document).ready(function() {
    $('select').material_select();
    $('#sucu_select').on('change', function() {
      $('#sucu').val($('#sucu_select').val());
    });
});
</script>

I added an id (id="sucu_select") to the select box and created the hidden input that will store (and post) the sucu value:

<input type="hidden" name="sucu" id="sucu" />

Then i added jQuery to update the hidden value:

$('#sucu_select').on('change', function() {
  $('#sucu').val($('#sucu_select').val());
});

May not fix the problem itself, but now you can get the selected value through params.

Upvotes: 1

Related Questions