Unobtrusive JS:使用表单中的复选框切换元素可见性

发布于 2024-11-04 03:51:58 字数 8146 浏览 1 评论 0原文

我正在学习如何编写不引人注目的 JavaScript,并且我已经能够解决大部分问题,但是我在使用复选框打开和关闭元素的可见性时遇到了麻烦。请记住,我首先是一名设计师,然后是程序员,哦,18 岁左右。换句话说,我在编程方面是一个新手。 (注:此表格适用于牙髓病学公司推荐表格,因此是行业术语)。

另外,请不要推荐 JQuery;我知道它存在,并且我经常使用它。我想学习如何用纯 Javascript 实际做到这一点。以下是重要的 HTML 片段(这是在 asp.NET 中创建的):

<ol>
<li>
    <fieldset>
        <legend>Which of these procedures is required? (select at least one)<span class="required"> *</span></legend>
        <label id="procedure01"><asp:CheckBox ID="chkEndodonticProcedure01" GroupName="EndodonticProcedure" runat="server" />Consultation for evaluation of tooth</label>
        <label id="procedure02"><asp:CheckBox ID="chkEndodonticProcedure02" GroupName="EndodonticProcedure" runat="server" />Re-treatment of tooth</label>
        <label id="procedure03"><asp:CheckBox ID="chkEndodonticProcedure03" GroupName="EndodonticProcedure" runat="server" />Treatment of tooth</label>
    </fieldset>
    <ol id="consultation">
        <li>
            <asp:Label ID="lblConsultationToothNumber" AssociatedControlID="txtConsultationToothNumber" runat="server">Consultation tooth number</asp:Label>
            <asp:TextBox id="txtConsultationToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <fieldset>
                <legend>Do any of these conditions apply?</legend>
                <label><asp:CheckBox ID="chkToothCondition01" GroupName="ToothCondition" runat="server" />Vague toothache</label>
                <label><asp:CheckBox ID="chkToothCondition02" GroupName="ToothCondition" runat="server" />Pain, swelling</label>
                <label><asp:CheckBox ID="chkToothCondition03" GroupName="ToothCondition" runat="server" />Sensitivity to heat</label>
                <label><asp:CheckBox ID="chkToothCondition04" GroupName="ToothCondition" runat="server" />Sensitivity to cold</label>
                <label><asp:CheckBox ID="chkToothCondition05" GroupName="ToothCondition" runat="server" />Sensitivity to percussion</label>
                <label><asp:CheckBox ID="chkToothCondition06" GroupName="ToothCondition" runat="server" />Possible combined perio-endo lesion</label>
                <label><asp:CheckBox ID="chkToothCondition07" GroupName="ToothCondition" runat="server" />Suspected cracked tooth/root</label>
            </fieldset>
        </li>
    </ol>
    <ol id="retreatment">
        <li>
            <asp:Label ID="lblRetreatmentToothNumber" AssociatedControlID="txtRetreatmentToothNumber" runat="server">Re-treatment tooth number</asp:Label>
            <asp:TextBox id="txtRetreatmentToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <asp:Label ID="lblPreviousRCTDate" AssociatedControlID="txtPreviousRCTDate" runat="server">Date of previous RCT</asp:Label>
            <asp:TextBox id="txtPreviousRCTDate" CssClass="textbox datepicker" runat="server" />
        </li>
    </ol>
    <ol id="treatment">
        <li>
            <asp:Label ID="lblTreatmentToothNumber" AssociatedControlID="txtTreatmentToothNumber" runat="server">Treatment tooth number</asp:Label>
            <asp:TextBox id="txtTreatmentToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <fieldset>
                <legend>What is the reason for treatment? (check any that apply)</legend>
                <label><asp:CheckBox ID="chkTreatmentReason01" GroupName="TreatmentReason" runat="server" />Necessary for proper restoration</label>
                <label><asp:CheckBox ID="chkTreatmentReason02" GroupName="TreatmentReason" runat="server" />Pulp exposed and vital</label>
                <label><asp:CheckBox ID="chkTreatmentReason03" GroupName="TreatmentReason" runat="server" />Pulp exposed and non-vital</label>
                <label><asp:CheckBox ID="chkTreatmentReason04" GroupName="TreatmentReason" runat="server" />Tooth was opened and medicated</label>
                <label><asp:CheckBox ID="chkTreatmentReason05" GroupName="TreatmentReason" runat="server" />X-ray revealed radiolucency/pulpal involvement</label>
            </fieldset>
        </li>
        <li>
            <fieldset>
                <legend>Is an X-ray included for revealed radiolucency/pulpal involvement?</legend>
                <label><asp:RadioButton ID="rdoXrayIncluded01" GroupName="XrayIncluded" runat="server" />Yes</label>
                <label><asp:RadioButton ID="rdoXrayIncluded02" GroupName="XrayIncluded" runat="server" />No</label>
            </fieldset>
        </li>
    </ol>
</li>

使用不显眼的 Javascript,我获取表单 ID(“referralform”),创建两个数组来包含相关元素 ID,隐藏我想要使用 CSS 类关闭的元素,然后应用 onclick 事件来应用显示的 CSS 类元素:

function prepareAccordion()
{
if (document.getElementById && document.getElementsByTagName)
{
    if (document.getElementById("referralform"))
    {
        var accordionids = new Array();
        accordionids[0] = document.getElementById("minorparent");
        accordionids[1] = document.getElementById("consultation");
        accordionids[2] = document.getElementById("retreatment");
        accordionids[3] = document.getElementById("treatment");

        var revealids = new Array();
        revealids[0] = document.getElementById("minorYes");
        revealids[1] = document.getElementById("minorNo");
        revealids[2] = document.getElementById("procedure01");
        revealids[3] = document.getElementById("procedure02");
        revealids[4] = document.getElementById("procedure03");

        for (var i = 0; i < accordionids.length; i++)
        {
            accordionids[i].className = "accordion-collapsed";
        }

        revealids[0].onclick = function revealAccordion()
        {
            accordionids[0].className = "accordion-revealed";
        }

        revealids[1].onclick = function revealAccordion()
        {
            accordionids[0].className = "accordion-collapsed";
        }

        x = 0;
        revealids[2].onclick = function revealAccordion()
        {
            if (x == 0)
            {
                accordionids[1].className = "accordion-revealed";
                x++;
            }
            else
            {
                accordionids[1].className = "accordion-collapsed";
                x--;
            }
        }

        y = 0;
        revealids[3].onclick = function revealAccordion()
        {
            if (y == 0)
            {
                accordionids[2].className = "accordion-revealed";
                y = 1;
            }
            else
            {
                accordionids[2].className = "accordion-collapsed";
                y = 0;
            }
        }

        z = 0;
        revealids[4].onclick = function revealAccordion()
        {
            if (z == 0)
            {
                accordionids[3].className = "accordion-revealed";
                z = 1;
            }
            else
            {
                accordionids[3].className = "accordion-collapsed";
                z = 0;
            }
        }
    }
}
}

function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
    window.onload = func;
}
else
{
    window.onload = function ()
    {
        if (oldonload)
        {
            oldonload();
        }
        func();
    }
}
}

addLoadEvent(prepareAccordion);

可能有一种更好的方法来为复选框创建“开/关”切换设置,而不是使用“1”和“0”并在它们之间切换,但同样,我不是程序员。问题是,当应用“1”和“0”之间的翻转时,onclick 事件仅在直接单击复选框时起作用,而不是在标签上起作用。当应用于单选按钮的标签时,onclick 工作得很好,所以一定是“1”和“0”之间的翻转导致了一些问题。

非常感谢任何对此的帮助。

I am learning how to write unobtrusive Javascript, and I've been able to work most things out, but I'm having trouble with toggling an element's visibility on and off using a checkbox. Keep in mind that I am a designer first, programmer, oh 18th or so. In other words, I am a novice when it comes to programming. (Note: This form is for an endodontics firm referral form, hence the industry terms).

Also, please do not suggest JQuery; I know it exists, and I use it often. I want to learn how to actually do this in pure Javascript. Here are the important HTML snippets (this is created in asp.NET):

<ol>
<li>
    <fieldset>
        <legend>Which of these procedures is required? (select at least one)<span class="required"> *</span></legend>
        <label id="procedure01"><asp:CheckBox ID="chkEndodonticProcedure01" GroupName="EndodonticProcedure" runat="server" />Consultation for evaluation of tooth</label>
        <label id="procedure02"><asp:CheckBox ID="chkEndodonticProcedure02" GroupName="EndodonticProcedure" runat="server" />Re-treatment of tooth</label>
        <label id="procedure03"><asp:CheckBox ID="chkEndodonticProcedure03" GroupName="EndodonticProcedure" runat="server" />Treatment of tooth</label>
    </fieldset>
    <ol id="consultation">
        <li>
            <asp:Label ID="lblConsultationToothNumber" AssociatedControlID="txtConsultationToothNumber" runat="server">Consultation tooth number</asp:Label>
            <asp:TextBox id="txtConsultationToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <fieldset>
                <legend>Do any of these conditions apply?</legend>
                <label><asp:CheckBox ID="chkToothCondition01" GroupName="ToothCondition" runat="server" />Vague toothache</label>
                <label><asp:CheckBox ID="chkToothCondition02" GroupName="ToothCondition" runat="server" />Pain, swelling</label>
                <label><asp:CheckBox ID="chkToothCondition03" GroupName="ToothCondition" runat="server" />Sensitivity to heat</label>
                <label><asp:CheckBox ID="chkToothCondition04" GroupName="ToothCondition" runat="server" />Sensitivity to cold</label>
                <label><asp:CheckBox ID="chkToothCondition05" GroupName="ToothCondition" runat="server" />Sensitivity to percussion</label>
                <label><asp:CheckBox ID="chkToothCondition06" GroupName="ToothCondition" runat="server" />Possible combined perio-endo lesion</label>
                <label><asp:CheckBox ID="chkToothCondition07" GroupName="ToothCondition" runat="server" />Suspected cracked tooth/root</label>
            </fieldset>
        </li>
    </ol>
    <ol id="retreatment">
        <li>
            <asp:Label ID="lblRetreatmentToothNumber" AssociatedControlID="txtRetreatmentToothNumber" runat="server">Re-treatment tooth number</asp:Label>
            <asp:TextBox id="txtRetreatmentToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <asp:Label ID="lblPreviousRCTDate" AssociatedControlID="txtPreviousRCTDate" runat="server">Date of previous RCT</asp:Label>
            <asp:TextBox id="txtPreviousRCTDate" CssClass="textbox datepicker" runat="server" />
        </li>
    </ol>
    <ol id="treatment">
        <li>
            <asp:Label ID="lblTreatmentToothNumber" AssociatedControlID="txtTreatmentToothNumber" runat="server">Treatment tooth number</asp:Label>
            <asp:TextBox id="txtTreatmentToothNumber" CssClass="textbox" runat="server" />
        </li>
        <li>
            <fieldset>
                <legend>What is the reason for treatment? (check any that apply)</legend>
                <label><asp:CheckBox ID="chkTreatmentReason01" GroupName="TreatmentReason" runat="server" />Necessary for proper restoration</label>
                <label><asp:CheckBox ID="chkTreatmentReason02" GroupName="TreatmentReason" runat="server" />Pulp exposed and vital</label>
                <label><asp:CheckBox ID="chkTreatmentReason03" GroupName="TreatmentReason" runat="server" />Pulp exposed and non-vital</label>
                <label><asp:CheckBox ID="chkTreatmentReason04" GroupName="TreatmentReason" runat="server" />Tooth was opened and medicated</label>
                <label><asp:CheckBox ID="chkTreatmentReason05" GroupName="TreatmentReason" runat="server" />X-ray revealed radiolucency/pulpal involvement</label>
            </fieldset>
        </li>
        <li>
            <fieldset>
                <legend>Is an X-ray included for revealed radiolucency/pulpal involvement?</legend>
                <label><asp:RadioButton ID="rdoXrayIncluded01" GroupName="XrayIncluded" runat="server" />Yes</label>
                <label><asp:RadioButton ID="rdoXrayIncluded02" GroupName="XrayIncluded" runat="server" />No</label>
            </fieldset>
        </li>
    </ol>
</li>

Using unobtrusive Javascript, I grab the form ID ("referralform"), create two arrays to contain the related element IDs, hide the elements I want turned off with a CSS class, and then apply the onclick event to apply the CSS class that reveals the elements:

function prepareAccordion()
{
if (document.getElementById && document.getElementsByTagName)
{
    if (document.getElementById("referralform"))
    {
        var accordionids = new Array();
        accordionids[0] = document.getElementById("minorparent");
        accordionids[1] = document.getElementById("consultation");
        accordionids[2] = document.getElementById("retreatment");
        accordionids[3] = document.getElementById("treatment");

        var revealids = new Array();
        revealids[0] = document.getElementById("minorYes");
        revealids[1] = document.getElementById("minorNo");
        revealids[2] = document.getElementById("procedure01");
        revealids[3] = document.getElementById("procedure02");
        revealids[4] = document.getElementById("procedure03");

        for (var i = 0; i < accordionids.length; i++)
        {
            accordionids[i].className = "accordion-collapsed";
        }

        revealids[0].onclick = function revealAccordion()
        {
            accordionids[0].className = "accordion-revealed";
        }

        revealids[1].onclick = function revealAccordion()
        {
            accordionids[0].className = "accordion-collapsed";
        }

        x = 0;
        revealids[2].onclick = function revealAccordion()
        {
            if (x == 0)
            {
                accordionids[1].className = "accordion-revealed";
                x++;
            }
            else
            {
                accordionids[1].className = "accordion-collapsed";
                x--;
            }
        }

        y = 0;
        revealids[3].onclick = function revealAccordion()
        {
            if (y == 0)
            {
                accordionids[2].className = "accordion-revealed";
                y = 1;
            }
            else
            {
                accordionids[2].className = "accordion-collapsed";
                y = 0;
            }
        }

        z = 0;
        revealids[4].onclick = function revealAccordion()
        {
            if (z == 0)
            {
                accordionids[3].className = "accordion-revealed";
                z = 1;
            }
            else
            {
                accordionids[3].className = "accordion-collapsed";
                z = 0;
            }
        }
    }
}
}

function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
    window.onload = func;
}
else
{
    window.onload = function ()
    {
        if (oldonload)
        {
            oldonload();
        }
        func();
    }
}
}

addLoadEvent(prepareAccordion);

There is likely a much better way to create "on/off" toggle settings for checkboxes than using "1" and "0" and flipping between them, but again, I'm not a programmer. The issue is that when applying the flip between "1" and "0", the onclick event only works when directly clicking within the checkbox, and not on the label. The onclick works fine when applied to a radio button's label, so it must be the flip between "1" and "0" that is throwing something off.

Any help with this is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终陌 2024-11-11 03:51:58

我会做的——事实上我为我雇主的网站所做的——是用一个类“toggleOnSwitch”来标记页面元素(我倾向于使用这样令人恼火的长名称)。该元素还将具有几个“data-”属性:“data-switch”,包含复选框或单选按钮或控制切换的 元素的“id”值; “data-toggle-class”,包含要打开和关闭的类(例如“隐藏”或“非活动”或其他);也许还有一两个我忘记了。

不显眼的 JavaScript 会查找该类,然后为每个切换元素在 switch 元素(在您的例子中为复选框)上设置事件处理程序。事件处理程序执行从切换元素添加/删除类的工作。

如果您想打开单选按钮,情况会稍微复杂一些,因为当一个单选按钮打开时,它的所有朋友都会关闭,因此处理程序必须知道触发所有其他同名单选按钮上的切换处理程序,以防它们还控制页面元素可见性(或添加/删除的类所做的任何操作)。我还对我的代码进行了编码,以便如果“data-switch”值以“!”开头,例如“!toggleCheckbox”,那么这意味着反转切换的意义。当某个特定的复选框在关闭一件事的同时又打开另一件事时,这很方便。

What I would do — and, in fact what I do for my employer's site — is to mark page elements with a class, "toggleOnSwitch" (I tend to use irritating long names like that). The element will then also have a couple of "data-" attributes: "data-switch", containing the "id" value for the checkbox or radio button or <option> element that controls the toggling; "data-toggle-class", containing the class to toggle on and off (like, "hidden" or "inactive" or whatever); and maybe one or two others I'm forgetting.

The unobtrusive JavaScript looks for that class, and then for each toggled element it sets up event handlers on the switch element (the checkbox, in your case). The event handlers do the work of adding/removing the class from the toggled element.

It's a little more complicated than that if you want to toggle on radio buttons, because when one radio button switches on, all its friends switch off, so the handler has to know to trigger the toggle handlers on all the other radio buttons with the same name, in case they also control page element visibility (or whatever the added/removed class does). I also coded mine so that if the "data-switch" value starts with a "!", like "!toggleCheckbox", then that means to reverse the sense of the toggle. That's handy when a particular checkbox switches one thing off at the same time it switches another thing on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文