简体   繁体   English

如何使用带有Javascript的复选框禁用/启用表单元素?

[英]How to disable/enable form elements using a checkbox with Javascript?

I'm at a loss - after wracking my brain for hours on this one, it's time to throw the question up here. 我不知所措 - 在这个问题上我的大脑被砸了几个小时后,是时候把问题提到这里了。

I'm trying to have a checkbox execute some javascript code that, when checked, enables some form elements, and when unchecked, disables those elements again. 我试图让一个复选框执行一些javascript代码,当选中它们时,启用一些表单元素,并且当取消选中时,再次禁用这些元素。

Here's the javascript that I have: 这是我的javascript:

function houseclean()
{
if (document.orderform.cleaning.checked == true)
  {
  document.orderform.rooms.disabled = false;
  document.orderform.datetime.disabled = false;
  document.orderform.howoften.disabled = false;
  }
else
  {
  document.orderform.rooms.disabled = true;
  document.orderform.datetime.disabled = true;
  document.orderform.howoften.disabled = true;
  }
} 

And here is my HTML code: 这是我的HTML代码:

<form id="orderform" style="margin-left: 6cm">
<input type="checkbox" name="cleaning" value="yes" onclick="houseclean()"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
  <option value="1bedroom">One Bedroom Apt</option>
  <option value="2bedroom">Two Bedroom Apt</option>
  <option value="3bedroom">Three Bedroom Townhome or SF Home</option>
  <option value="4bedroom">Four Bedroom Home</option>
  <option value="5bedroom">Five Bedroom Home</option>
  <option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" name="datetime" disabled /><br />
How often would you like a cleaning?: <select name="howoften" disabled>
  <option value="once">One Time Only</option>
  <option value="2bedroom">Every Week</option>
  <option value="3bedroom">Every Other Week</option>
  <option value="4bedroom">Once a Month</option>
</select> <br />
</form>

This code will do the trick. 这段代码可以解决问题。 You should be explicit about your element IDs and use getElementById whenever possible. 您应该明确说明您的元素ID,并尽可能使用getElementById。

The HTML: HTML:

<form id="orderform" style="margin-left: 6cm;">
<input type="checkbox" id="cleaning" name="cleaning" value="yes" onclick="javascript:houseclean();"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
  <option value="1bedroom">One Bedroom Apt</option>
  <option value="2bedroom">Two Bedroom Apt</option>
  <option value="3bedroom">Three Bedroom Townhome or SF Home</option>
  <option value="4bedroom">Four Bedroom Home</option>
  <option value="5bedroom">Five Bedroom Home</option>
  <option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" id="datetime" name="datetime" disabled /><br />
How often would you like a cleaning?: <select id="howoften" name="howoften" disabled>
  <option value="once">One Time Only</option>
  <option value="2bedroom">Every Week</option>
  <option value="3bedroom">Every Other Week</option>
  <option value="4bedroom">Once a Month</option>
</select> <br />
</form>​

And the javascript: 和javascript:

function houseclean()
{
if (document.getElementById('cleaning').checked == true)
  {
  document.getElementById('rooms').removeAttribute('disabled');
  document.getElementById('datetime').removeAttribute('disabled');
  document.getElementById('howoften').removeAttribute('disabled');
  }
else
  {
  document.getElementById('rooms').setAttribute('disabled','disabled');
  document.getElementById('datetime').setAttribute('disabled','disabled');
  document.getElementById('howoften').setAttribute('disabled','disabled');
  }
}

JSFiddle example: http://jsfiddle.net/HQQ4n/10/ JSFiddle示例: http//jsfiddle.net/HQQ4n/10/

I got your code to work. 我让你的代码工作。 I added the id attribute to the form elements and used document.getElementById to be on the safe side. 我将id属性添加到表单元素中,并使用document.getElementById来保证安全。

JFiddle example: http://jsfiddle.net/vxRjw/1/ JFiddle示例: http//jsfiddle.net/vxRjw/1/

Not super robust, but a dynamic jquery solution... 不是超级健壮,而是一个动态的jquery解决方案......

$("#mycheckbox").click(function() {
  enableFormElements("#myform", $(this).attr('checked'));
});

function enableFormElements(form, enable) {
        var fields = ["checkbox","textarea","select"];
        var selector = form+" input";
        $.each(fields, function(i,e) { selector += ","+form+" "+e; });
        $(selector).each(function(idx) {
            if (enable) {
                $(this).removeAttr("disabled");
                $(this).removeAttr("readonly");
            } else {
                $(this).attr("disabled","disabled");
                $(this).attr("readonly","readonly");
            }
            if ($(this).is("select") || $(this).is("textarea")) {
                var id = $(this).attr("id");
                var txt_equiv = id+"_text";
                var val = $(this).find("option[value='"+$(this).val()+"']").text();
                // dynamically add the span to this element...so you can switch back and forth...
                if ($(this).parent().find("span").length == 0) {
                    $(this).parent().append("<span class='record_display_text' id='"+txt_equiv+"'>"+val+"</span>");
                }
            }
            if ($("#"+txt_equiv).length != 0) {
                if (enable) {
                    $("#"+id).show();
                    $("#"+txt_equiv).hide();
                } else {
                    $("#"+txt_equiv).show();
                    $("#"+id).hide();
                }
            }
        });
}

The function basically looks for all input, selects, textareas found inside the element provided and disables or enables each one. 该函数基本上查找所提供的元素内的所有输入,选择,textareas,并禁用或启用每个。 If using JQuery 1.9, you may want to change those to prop settings, but I've found that not all browsers are consistently working with that yet. 如果使用JQuery 1.9,您可能希望将它们更改为prop设置,但我发现并非所有浏览器都在使用它。 (bleh). (的Bleh)。 In the cases of textareas or selects, it actually creates a related span with an id that matches the input except with "_text" after it. 在textareas或choose的情况下,它实际上创建了一个相关的span,其id与输入匹配,除了后面带有“_text”。 If you have other IDs on your page that might conflict, you might want to edit that...but putting that in place allows the code later to hide/show either the text or the actual select/textarea depending on whether you want everything enabled or disabled. 如果您的页面上有其他可能存在冲突的ID,您可能需要对其进行编辑...但是将其置于适当的位置后,代码可以隐藏/显示文本或实际的select / textarea,具体取决于您是否要启用所有内容或者禁用。 Again, not tested in all circumstances, but feel free to copy and edit for your purposes... 同样,没有在所有情况下进行测试,但可以随意复制和编辑...

Oh, and make sure that all selects or textareas are an only child to their parent...wrap in a span if you have to because it dynamically adds the related span within the same parent...so if the select or textarea isn't wrapped in a parent (like a span, a div, or a td or something), then it might throw the generated text span somewhere random. 哦,并确保所有选择或textareas是他们父母的唯一孩子...如果你必须在一个范围内换行,因为它在同一个父母中动态添加相关的跨度......所以如果select或textarea是' t包裹在父级(如span,div或td或其他东西)中,然后它可能会将生成的文本跨度随机抛出。 :P :P

And then you can add some CSS to make form elements look more like your normal page or standard span elements... 然后你可以添加一些CSS来使表单元素看起来更像你的普通页面或标准span元素...

    input[readonly],
    select[readonly],
    textarea[readonly] {
      cursor: default;
    }

    input[disabled] {
        background-color:#F0F0F0;
        border:none;
        -moz-box-shadow: none;
        -webkit-box-shadow:none;
        box-shadow:none;
        padding: 0;
    }

You will probably want to change the background-color to match your page color...and the "cursor:default" one is if bootstrap twitter is adding the annoying "restricted" cursor or whatever it is over disabled elements...but anyways, this is a solution I came up with this evening and it's working for me. 您可能希望更改背景颜色以匹配您的页面颜色...而“游标:默认”一个是如果bootstrap twitter正在添加恼人的“受限制”光标或其他任何残障元素......但无论如何,这是我今晚提出的解决方案,它对我有用。 :) :)

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

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