简体   繁体   English

Select2 不选择第一项作为默认值

[英]Select2 not selecting first item as default

I am populating a drop down list in an ASP.Net page using this code我正在使用此代码在 ASP.Net 页面中填充下拉列表

var xhttp

        xhttp = new XMLHttpRequest();
        xhttp.open("GET", "../XMLHttp/XMLHttp_GetRDRegions.aspx?RDDivision=" + encodeURIComponent(document.getElementById('ddlRDDivisions').value), false);
        xhttp.send();

        document.getElementById('ddlRDRegions').options.length = 0;
        document.getElementById('ddlRDCentres').options.length = 0;
        document.getElementById('ddlRMNames').options.length = 0;

        var ddlRDRegions = document.getElementById('ddlRDRegions');
        var element = document.createElement('option');
        element.text = '--- Please Select an item ---'
        element.value = '0'
        ddlRDRegions.options.add(element);

When not using Select the new element I am adding is the first selected item in the list, however when applying the Select2 in the javascript too like this.当不使用 Select 时,我添加的新元素是列表中的第一个选定项,但是在 javascript 中应用 Select2 时也像这样。

$('select').select2();

the element is at the top of the list but is not the selected element.该元素位于列表顶部,但不是所选元素。

I have tried creating an attribute like this我曾尝试创建这样的属性

var att = document.createAttribute("selected");
att.value = "selected";
element.setAttribute(att)

which throws an error and this这引发了一个错误,这

$(element).attr("selected", "selected")

which does nothing.什么都不做。

Any and all help on where I am going wrong would be very much appreciated.任何和所有关于我哪里出错的帮助都将不胜感激。

我现在找到了根本不明显的答案......

$(ddlRDRegions ).select2().select2('val','ddlRDRegions.selectedindex')

For attr('selected', 'selected');对于 attr('selected', 'selected'); you need to add this to your option tag.您需要将此添加到您的选项标签。

And for this $('#ddlRDRegions').val('0');而对于这个 $('#ddlRDRegions').val('0');

 $('#test').on('click', function(){ $("#font_family").val('arial'); }); $('#test2').on('click', function(){ $("#heltest").attr('selected', 'selected'); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="font_family" class="form-control" name="font_family"> <option value="0">---Select Font---</option> <option value="tnr">Times New Roman</option> <option id='heltest' value="helvetica">Helvetica</option> <option value="verdana">Verdana</option> <option value="arial">Arial</option> </select> <button id='test'>Click Me For Arial</button> <button id='test2'>Click Me For Helvetica</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM