Change value of materialize select box by jquery

前端 未结 11 1364
滥情空心
滥情空心 2020-12-29 22:18

I want to change materialize select box value by jquery.

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

相关标签:
11条回答
  • 2020-12-29 22:52

    For a new materialize 1.0.0 use .select() instead of .material_select()

    Solution without re-initialization.

    function msValue (selector, value) {
     selector.val(value).closest('.select-wrapper').find('li').removeClass("active").closest('.select-wrapper').find('.select-dropdown').val(value).find('span:contains(' + value + ')').parent().addClass('selected active');
    }
    

    Then just use

    msValue($("#select_id"), "value_here")
    
    0 讨论(0)
  • 2020-12-29 22:53
    $('#myselect').formSelect() ;
    

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

    0 讨论(0)
  • 2020-12-29 22:53

    In 2018 (Materialize v1.0.0-rc.2), first you have to set your option programmatically:

    $('#SELECT-ID').find('option[value="SELECT-VALUE"]').prop('selected', true);
    

    And then re-initialise the select input with:

    $("#SELECT-ID").formSelect();
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-29 22:56

    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();
        });
    });
    
    0 讨论(0)
  • 2020-12-29 22:56

    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();    
    });
    
    0 讨论(0)
提交回复
热议问题