2

How can I programmatically select an option from select in Materialize css? I tried to append the value for select with its first option.

Any help would be much appreciated.

Thanks.

$('select').material_select();
$('#select_1').val($('#select_1 option:first').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">


<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>

<div class="row">
  <div class="input-field col s12">
    <select id="select_1" name="select_1">
      <option disabled selected>Choose your option</option>
      <option>Option 1</option>
      <option>Option 2</option>
      <option>Option 3</option>
      <option>Option 4</option>
      <option>Option 5</option>
      <option>Option 6</option>
    </select>
    <label for="select_1">Select 1</label>
  </div>
</div>
Inchara Raveendra
  • 1,617
  • 3
  • 15
  • 31

1 Answers1

3

You just need to call the material_select() on it again.

Keep in mind though that the :first you use to select the option targets the <option disabled selected>Choose your option</option> one.

$(function(){
  $('select').material_select();
 
  var select = $('#select_1');
  
  select.find('option:eq(2)').prop('selected', true);
  select.material_select();
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>

<div class="row">
  <div class="input-field col s12">
    <select id="select_1" name="select_1">
      <option disabled selected>Choose your option</option>
      <option>Option 1</option>
      <option>Option 2</option>
      <option>Option 3</option>
      <option>Option 4</option>
      <option>Option 5</option>
      <option>Option 6</option>
    </select>
    <label for="select_1">Select 1</label>
  </div>
</div>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317