GetElementById возвращает неопределенное значение - PullRequest
0 голосов
/ 15 ноября 2018

У меня есть CheckboxList с 3 вариантами.

В моем javascript я хочу проверить, какие опции отмечены галочкой.

Но проверка не прошла, поскольку полученное значение var равно undefined.

JavaScript: РЕДАКТИРОВАТЬ

var schedule = document.getElementById("<%=ddlExecutionSchedule.ClientID%>").value; 
// ^ return as undefined

var schedule2 = document.getElementById("ddlExecutionSchedule").value;
// ^ return as undefined

var scheduleOptions = schedule.getElementsByTagName('input'); 
// ^ error: Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined

HTML:

<div class="form-group" id="divExecutionSchedule">
<label class="control-label col-md-2" id="lblExecutionSchedule">Execution Schedule</label>
<div class="col-md-3">
    <div class="input-group">
        <asp:CheckboxList ID="ddlExecutionSchedule" ClientIDMode="Static" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleExecutionSchedule(this)" >
            <asp:ListItem Text="Daily" Value="Daily"></asp:ListItem>
            <asp:ListItem Text="Weekly" Value="Weekly"></asp:ListItem>
            <asp:ListItem Text="Monthly" Value="Monthly"></asp:ListItem>
        </asp:CheckboxList>
    </div>
</div>

C #:

//if (ddlExecutionSchedule.Text == "Weekly") // <= Commented off to allow catering for multiple checkboxes to be ticked at the same time
    //{
    string selectedDay = item["Days"] != null ? item["Days"].ToString() : string.Empty;

    if (!string.IsNullOrEmpty(selectedDay))
    {
        List<string> day = selectedDay.Replace(";#",";").Split(';').ToList();
        for (int i = 0; i < chkSelectDay.Items.Count; i++)
        {
            if (day.Contains(chkSelectDay.Items[i].Value))
            {
                //Check only if they match! 
                chkSelectDay.Items[i].Selected = true;
            }
        }
    }
//}

Я просмотрел аналогичные статьи и попробовал несколько способов, включая добавление в GetElementsByTagName, но нажал Uncaught TypeError.

Любая помощь очень ценится.

Ответы [ 3 ]

0 голосов
/ 15 ноября 2018

Можете ли вы попробовать удалить двойные кавычки, т.е. "" около "<%=ddlExecutionSchedule.ClientID%>" в js и просто оставить (<%=ddlExecutionSchedule.ClientID%>).

это может помочь тебе

0 голосов
/ 15 ноября 2018

Пожалуйста, удалите ClientIDMode="Static" из приведенного ниже кода.

<asp:CheckboxList ID="ddlExecutionSchedule" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleExecutionSchedule(this)" >
    <asp:ListItem Text="Daily" Value="Daily"></asp:ListItem>
    <asp:ListItem Text="Weekly" Value="Weekly"></asp:ListItem>
    <asp:ListItem Text="Monthly" Value="Monthly"></asp:ListItem>
</asp:CheckboxList>

или если вы хотите продолжить с ClientIDMode="Static", напишите синтаксис JS следующим образом.

var schedule = document.getElementById("ddlExecutionSchedule").value;

это может вам помочь.

0 голосов
/ 15 ноября 2018

Возвращается undefined, так как контейнер списка флажков не имеет никакого значения, поэтому,

Вам необходимо перебрать список CheckBox, чтобы получить значения проверенных значений, таких как:

Редактировать: как вы указали ClientIDMode="Static", чтобы он не изменялся во время выполнения, поэтому вы можете напрямую указать идентификатор контейнера

        //var chkBox = document.getElementById('<%= ddlExecutionSchedule.ClientID %>');
        var chkBox = document.getElementById('ddlExecutionSchedule');
        var options = chkBox.getElementsByTagName('input');
        var listOfSpans = chkBox.getElementsByTagName('span'); //change 'span' as per the page structure
        for (var i = 0; i < options.length; i++)
        {
            if(options[i].checked)
            {
                alert(listOfSpans[i].attributes["JSvalue"].value); //change attribute as per the page structure
            }
        }
...