2016-07-23 128 views
1

我正在使用select2 v4.0.3以及JQuery。 我初始化我的选择是:select2显示不更新标签文本,但值正在更改

$("#datatype").select2({ 
     theme: "classic" 
     }); 

$("#unit").select2({ 
     theme: "classic" 
     }); 

然后我想,以检测#datatype的改变,改变的#unit价值这一点我如下:

$("#datatype").on('select2:select',function() { 
    $("#unit").val('21'); //udpate unit type to be 'none' 
    }); 

的问题是,#unit值设置为21,但该选择器的显示标签未更新。有什么建议么 ?

看起来好像select2不知道该事件,或者它没有正确设置以聆听变化。我不确定解决方案是什么。我对网络技术很陌生。

回答

0

通过选择二文档挖掘之后,任何.val()更新需要被随后$('#unit').trigger('change');

所以在我的情况下,代码应该看起来像

$("#datatype").on('select2:select',function() { 
    $('#unit').val('21'); // Select the option with a value of '21' 
    $('#unit').trigger('change'); // Notify any JS components that the value changed 
}); 

注意,这是唯一真正的选择2版4以上。

我还建议人们升级到版本4,因为您可以直接调用以更改值而无需指定initSelect()