Change value of materialize select box by jquery

前端 未结 11 1363
滥情空心
滥情空心 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:37

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

    This was my solution in case it helps someone. I used a lot of what @Raold said. the issue I had was the select was getting stuck when it's updated without the code below.

    function updateSelect(value) {
        var select  =  $('#myselectId');
        $(select).val(value);
        var text = $(select).find(':selected').text();
        $(select).closest('.select-wrapper')
            .find('li').removeClass("active")
            .closest('.select-wrapper')
            .find('.select-dropdown').val(text)
            .find('span:contains(' + value + ')')
            .parent()
            .addClass('selected active');
    }
    
    0 讨论(0)
  • 2020-12-29 22:38

    As suggested by @logikal, you have got to re-Initialize

    $("#myselect").material_select()
    
    0 讨论(0)
  • 2020-12-29 22:41

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

    Solution, I used in my project:

    document.getElementById("mySelect").addEventListener("change", function()
    {
      console.log("Hello, World!")
    });
    

    I don't know if the event trigger gives you selected item or selected item's value - you can check it yourself!

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

    This answer might be late but it might help someone else.

    On Ready add the line below

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

    Each time you change an option within your Select add the line below

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

    This is what worked for me, hope it helps.

    0 讨论(0)
提交回复
热议问题