【问题标题】:Change options in select with JavaScript without loosing chosen使用 JavaScript 在不丢失选择的情况下更改选择中的选项
【发布时间】:2019-05-22 10:02:46
【问题描述】:

我正在尝试使用 JavaScript 和 JQuery 重新加载选择的选项列表,但我需要保留以前选择的值。

这是我的代码:

    var temp = $('#SelectName').chosen().val();

    select = document.getElementById('SelectName');

    if (select.options.length > 0) {
        $('#SelectName').find('option').remove();
    }

    for (var i = 0; i < result.length; i++) {
        var option = document.createElement('option');
        option.value = result[i].myIdVariable;
        option.text = result[i].myTextVariable;
        select.appendChild(option); 
    }

    $('#SelectName').chosen(temp);

    $('#SelectName').trigger('chosen:updated');

使用此代码,我会丢失所有选择的值。

【问题讨论】:

    标签: javascript jquery jquery-chosen


    【解决方案1】:

    我用这段代码解决了:

    var temp = $('#SelectName').val();
    
    select = document.getElementById('SelectName');
    
    if (select.options.length > 0) {
        $('#SelectName').find('option').remove();
    }
    
    for (var i = 0; i < result.length; i++) {
        var option = document.createElement('option');
        option.value = result[i].myIdVariable;
        option.text = result[i].myTextVariable;
        select.appendChild(option); 
    }
    
    $('#SelectName').val(temp);
    
    $('#SelectName').trigger('chosen:updated');
    

    不同的是,我现在用的是:

    var temp = $('#SelectName').val();
    

    $('#SelectName').val(temp);
    

    以前:

    var temp = $('#SelectName').chosen().val();
    

    $('#SelectName').chosen(temp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2016-04-15
      • 2015-02-23
      • 1970-01-01
      • 2023-03-30
      • 2021-11-27
      相关资源
      最近更新 更多