Skip to content Skip to sidebar Skip to footer

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 checke

Solution 1:

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.net/HQQ4n/10/


Solution 2:

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.net/vxRjw/1/


Solution 3:

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


Post a Comment for "How To Disable/enable Form Elements Using A Checkbox With Javascript?"