简体   繁体   中英

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

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?

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

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.

不幸的是,materialze.css将<select>更改为基于<ul>和多个<li>的假选择,您可以尝试在生成的<li>上绑定事件,但这似乎很难:您无法绑定onchange如果你不使用browser-default类或者不搜索一下,在materialize.css <select>上的事件。

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.

Add change event listener when you initialize material select

$(document).ready(function(){          
          $('#somedropdown').material_select(someScope.someEvent.bind(someScope));
});

I am using materialize-css with angular7. This is how I have handled this

<div class="input-field col s12">
    <select #qwcSelect (change)="optionChanged($event)">
        <option value="" selected disabled>{{placeHolder}}</option>
        // options
    </select>
    <label>{{label}}</label>
</div>

and in my component

optionChanged(event) {
   console.log(`Selected Value ${event.target.value}`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM