Change value of materialize select box by jquery

2019-02-04 13:12发布

I want to change materialize select box value by jquery.

I am using $('#myselect').val('1'); on onchange event of other select box but it not works.

$("#select1").change(function() {
    $('#myselect').val('1');
});

9条回答
ゆ 、 Hurt°
2楼-- · 2019-02-04 13:42
$('#myselect').formSelect() ;

The new method is formSelect(), use this after you have updated the select.

查看更多
疯言疯语
3楼-- · 2019-02-04 13:51

Rather than using .val(), it's cleaner to set value as usual with jQuery :

$('#my-select').find('option[value="my-value"]').prop('selected', true);
$("#my-select").material_select();
查看更多
Bombasti
4楼-- · 2019-02-04 13:51

Using delegated event fixes the problem for me.

HTML

 <div class="input-field col s10" id="pickerContainer">
 <select>
            <option value="" disabled selected>Choose your option</option>
            </select>
          </div>

JS

$('#pickerContainer').on('change', 'select', function(){
 console.log("got you");
});
查看更多
Fickle 薄情
5楼-- · 2019-02-04 13:51

I found proper solution from here

For multiple in materialize

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

And now you just little change in your Javascript section and that is the url:

<script src="http://materializecss.com/bin/materialize.js" />

instead of

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

or any other link of materialize.min.js

And for multiple select enabling :

$(document).ready(function () {
        $('select').material_select();
    });

Thats it. You can check demo of this solution : JSFiddle

查看更多
干净又极端
6楼-- · 2019-02-04 13:57

This is similar to what logikal answered but I think is cleaner:

$(".your-component-class").change(function(){

   //your code..


   //re-initialize component
   $(this).material_select();    
});
查看更多
欢心
7楼-- · 2019-02-04 13:59

It appears to work fine for me, changing the first drop down, resets the value of the second drop down to 1.

I have done a rough implementation on jsFiddle: http://jsfiddle.net/55r8fgxy/1/

<select id="select1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

<select id="myselect">    
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

JS:

$(function() {
    $("#select1").on('change', function() {
        $('#myselect').val("1");

        // re-initialize material-select
        $('#myselect').material_select();
    });
});
查看更多
登录 后发表回答