1

Im trying to grab the value off the materialize select menu option via javascript and im not getting what I want

<div class="input-field col s12">
    <select>
      <option value="" disabled selected>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    <label>Materialize Select</label>
  </div>

For instance how would I get the value of option 3 via javascript?

Tevin Thuku
  • 437
  • 1
  • 8
  • 19

1 Answers1

-1

If you use AngularJS this can done easily. Following code get , selected value of option and display below. To run materializecss select should add relevant jquery code.

<script>
  $(document).ready(function() {
    $('select').material_select();
  });
</script>

<select ng-model="getValue"> assign selected value to getValue variable and you can use it as {{getValue}} withing the scope.

Note: When you add <script> tag order is important. If you change the position of <script> tags to wrong order following code will not work.

<!DOCTYPE html>
<html ng-app>

<head>
  <title>Select</title>
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body class="row">

  <!-- your code start -->
  <div class="input-field col s6">
    <select ng-model="getValue">
      <option value="" disabled selected>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    <label>Materialize Select</label>
  </div>
  <!-- your code end -->
  
  <!--Display result-->
  <h5 class="col s12">You select : {{getValue}}</h5>

  <!--Import jQuery before materialize.js-->
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>

  <!--Materializecss Select-->
  <script>
    $(document).ready(function() {
      $('select').material_select();
    });
  </script>

  <!--AngularJS CDN-->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</body>

</html>
Sandun Madola
  • 870
  • 2
  • 10
  • 26