最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to disableenable form elements using a checkbox with Javascript? - Stack Overflow

programmeradmin1浏览0评论

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.

Here's the javascript that I have:

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:

<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>

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.

Here's the javascript that I have:

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:

<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>
Share Improve this question asked Jul 20, 2012 at 17:54 James LiddycoatJames Liddycoat 91 gold badge2 silver badges3 bronze badges 1
  • Please elaborate on what the error is. Just from this I'd guess that document.orderform.blah.disabled isn't actually what you want, maybe use jQuery? Or maybe you want onclientclicked? – Andrew Hagner Commented Jul 20, 2012 at 18:01
Add a ment  | 

3 Answers 3

Reset to default 3

This code will do the trick. You should be explicit about your element IDs and use getElementById whenever possible.

The 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:

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/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.

JFiddle example: http://jsfiddle/vxRjw/1/

Not super robust, but a dynamic jquery solution...

$("#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. 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. (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. 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. 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. :P

And then you can add some CSS to make form elements look more like your normal page or standard span elements...

    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. :)

发布评论

评论列表(0)

  1. 暂无评论