Search code examples
reactjsmaterialize

Display selected option text within Dropdown of Materialize


I am using the Dropdown component in MaterializeCSS.

The following HTML works alright:

  <a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>
  <ul id='dropdown1' class='dropdown-content'>
    <li><a href="#!">one</a></li>
    <li><a href="#!">two</a></li>
    <li class="divider"></li>
    <li><a href="#!">three</a></li>
    <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
    <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
  </ul>

When the option is selected, it navigates to a link. But what I want to happen is, when the option is selected, the "Drop Me!" text is replaced by the text of the selected option. In this case, the text should be one, two, etc.

How do I do that? Thanks.


Solution

  • You can do this through jquery on click event trigger. Just find the value of li and set text of drop me to the value of clicked li. Below is the code snippet. I hope this helps..

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
    
      <!-- Compiled and minified JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
    </head>
    <body>
    <!-- Dropdown Trigger -->
      <a class='dropdown-button btn dropdownBtn' href='#' data-activates='dropdown1'>Drop Me!</a>
    
      <!-- Dropdown Structure -->
      <ul id='dropdown1' class='dropdown-content'>
        <li><a href="#!">one</a></li>
        <li><a href="#!">two</a></li>
        <li class="divider"></li>
        <li><a href="#!">three</a></li>
        <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
        <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
      </ul>
    <script type="text/javascript">
        $(document).ready(function(){
            $('.dropdown-button').dropdown('open');
        })
            $('#dropdown1 li').click(function(){
    
                a = $(this).text()
                $('.dropdownBtn').text(a)
            })
    </script>
    </body>
    </html>