How do I change selected value of select2 dropdown with JqGrid?

后端 未结 16 864
遥遥无期
遥遥无期 2020-11-27 10:27

I\'m using Oleg\'s select2 demo, but I am wondering whether it would be possible to change the currently selected value in the dropdown menu.

For example, if the fou

相关标签:
16条回答
  • 2020-11-27 10:41

    do this

     $('select#id').val(selectYear).select2();
    
    0 讨论(0)
  • 2020-11-27 10:43

    if you have ajax data source please refer this for bugs free

    https://select2.org/programmatic-control/add-select-clear-items

    // Set up the Select2 control

    $('#mySelect2').select2({
        ajax: {
            url: '/api/students'
        }
    });
    

    // Fetch the preselected item, and add to the control

    var studentSelect = $('#mySelect2');
    $.ajax({
        type: 'GET',
        url: '/api/students/s/' + studentId
    }).then(function (data) {
        // create the option and append to Select2
        var option = new Option(data.full_name, data.id, true, true);
        studentSelect.append(option).trigger('change');
    
        // manually trigger the `select2:select` event
        studentSelect.trigger({
            type: 'select2:select',
            params: {
                data: data
            }
        });
    });
    
    0 讨论(0)
  • 2020-11-27 10:46

    if you want to select a single value then use $('#select').val(1).change()

    if you want to select multiple values then set value in array so you can use this code $('#select').val([1,2,3]).change()

    0 讨论(0)
  • 2020-11-27 10:47

    My Expected code :

    $('#my-select').val('').change();
    

    working perfectly thank to @PanPipes for the usefull one.

    0 讨论(0)
  • 2020-11-27 10:49

    Having some troubles with setting a String option selected in a select2:

    With the option: "option string1 /option" used:

    $('#select').val("string1").change(); 
    

    BUT with an option with a value: option value "E" string1 /option :

    $('#select').val("E").change(); // you must enter the Value instead of the string
    

    Hopes this help someone struggling with the same issue.

    0 讨论(0)
  • 2020-11-27 10:53

    if you want to set a selected item when you know the text from drop down list and don't know the value, here is an example:

    Say you figured out a timezone and want to set it, but values has time_zone_id in them.

            var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            var $select2 = $('#time-zone');
            var selected = $select2.find("option:contains('"+timeZone+"')").val();
            $select2.val(selected).trigger('change.select2'); 
    
    0 讨论(0)
提交回复
热议问题