How to listen on <select> change events in materialize css

22,284

Solution 1

Add an id to select

 <select id="select1">
  <optgroup label="team 1">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
  </optgroup>
  <optgroup label="team 2">
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
  </optgroup>
</select>

Bind event listener through jquery using the id

$("#select1").on('change', function() {
    console.log($(this));
});

Hope this helps :-)

JSFiddle Example Here

Solution 2

I'm not sure how you are setting up the listener, but I tried out a basic case in codepen here: http://codepen.io/anon/pen/xVZZYy.

It definitely can detect changes as long as you place event listener onto the <select> element itself.

Solution 3

As you might know materialize adds it's own data-select-id so any Id you add to the select element will make it behave a bit unstable, what you can do is wrap your select element with a div and give it an ID then use jQuery to select that id and chain the select element like so..

<div id="select1">
 <select >
  <optgroup label="team 1">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
  </optgroup>
  <optgroup label="team 2">
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
  </optgroup>
</select>
</div>

and

$('#select1 select').on('change', function(){
    console.log("option selected!")
    // do your stuff here.
})

This worked for me.

Share:
22,284
user1432882
Author by

user1432882

Updated on May 30, 2020

Comments

  • user1432882
    user1432882 almost 4 years

    A simple jquery listener on change doesn't seem to work when use a materialize css select dropdown.

     $("#somedropdown").change(function() {
             alert("Element Changed");
          }); 
    

    1) How can I add a listener to detect when a materialize select element has changed?

    2) How do I get the select value in that case?

    • Freddy Sidauruk
      Freddy Sidauruk about 8 years
      i guess jquery work in every framework css, can you make simple demo in codepen or fiddle
    • WcPc
      WcPc about 8 years
      If you add your $("#somedropdown")-Element dynamically, try $(document).on("change", "#somedropdown", function() {});
  • Sunil Garg
    Sunil Garg over 5 years
    Not working and even option is not getting selected.. Better to put your code here as link can be expired.