Я пробовал различные способы установить раскрывающийся список безрезультатно. В инструментах разработчика я вижу изменение selectedIndex
соответствующим образом, и я вижу, что узел опции изменился с выбранного значения false
на выбранное значение true
. Но когда всплывающее модальное окно открывается, в раскрывающемся списке отображается первый вариант, который пуст. Если я закрою и снова открою всплывающее окно, он отобразит все, что я выбрал вручную. Как я могу программно установить значение dropdownlist?
Отметить
<%--Address Popup--%>
<div id="location_modal" class="reveal-modal modal_location" data-reveal>
<fieldset>
<legend>Locations(Update/New)</legend>
<div class="row">
<div class="large-4 columns">
<asp:Label ID="Label4" runat="server">Location:*</asp:Label>
<asp:DropDownList ID="ddLocationNames" runat="server" class="input_ddllocationName"></asp:DropDownList>
</div>
Js
locationNameId = 'MainContent_lvAddresses_lblAddressLocation_' + g_index
locationName = document.getElementById(locationNameId).innerHTML;
var select = document.getElementById("MainContent_ddLocationNames");
for (var i = 0; i <select.options.length; i++){
if(select.options[i].innerHTML == locationName){
//select.selectedIndex = i;
//$(".input_ddllocationName").selectedIndex = i;
select[i].selected = true;
}
else{
select[i].selected = false;
}
}
Droplist id: MainContent_ddLocationNames
1. selected="selected" value=""
2. value="1">TESTING
3. value="2">TESTING AGAIN
4. value="3">MY FAVORITE LOCATION
5. value="4">MGM GRAND BALLROOM A
Из-за основания в раскрывающемся списке есть "специальная" разметка.
В Js мне пришлось добавить дополнительные строки кода. Спасибо Google Dev Tools!
//Find out which row should be selected
var indexSave = 0;
for (var i = 0; i<select.options.length; i++){
if(select.options[i].innerHTML == locationName){
indexSave = i;
break;
}
}
//Set the current node to the Location Name
$('#MainContent_ddlLocationName').next().children().first().text(locationName);
//Remove all selections
$('.input_ddlLocationName ul li').each(function() {
$(this).removeClass("selected");
});
//Select the Location Name based on index
var selectLi = indexSave + 1;
$('.input_ddlLocationName ul li:nth-child(' + selectLi + ')').addClass("selected");
Если вы используете базовый JavaScript, это должно сработать.
locationName = document.getElementById(locationNameId).innerHTML;
var select = document.getElementByClassName("input_ddllocationName")[0];
for (var i = 0; i <select.options.length; i++){
if(select.options[i].innerHTML == locationName){
select.selectedIndex = i;
// OR select.value = select.options[i].value;
}
else{
select[i].selected = false;
}
}
Если на странице есть jQuery:
$(".input_ddllocationName").val(locationName);
Или locationNameId, в зависимости от которого атрибут value для параметров.