0

I've written the following code, which enables a textbox when the checkbox is checked. The code is working with a small defect. For the first time when we execute, the textbox is enabled irrespective of the checkbox is checked or unchecked. But after a couple of times, the code is working correctly. Please help me to find the bug.

<html>
<head>
    <title>SHOP ALL</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script language="javascript" src="addcart.js"></script>
        <script type="text/javascript">
            function enableDisable(bEnable, textBoxID)
            {
                document.getElementById(textBoxID).disabled = !bEnable
            }
        </script>
</head>
     <body>
<form>
        <table align="center"  width="100%" cellpadding="50px">
            <tr>
                <th> TICK ON THE THINGS YOU NEED </th>
                <th> PRODUCT </th>
                <th> DESCRIPTION </th>
                <th> NO OF ITEMS </th>
            </tr>
            <tr>
                <td><input type="checkbox" name="shoe" onclick="enableDisable(this.checked, '0')"></td>
                <td><img src="images/1.jpg" alt="shoe1" width="180px" height="200px"></td>
                <td><h4>-------</h4></td>
                            </tr>
                        --------------
 </body>
</html`>

1 Answer 1

1

You should put your code:

    <script type="text/javascript">
        function enableDisable(bEnable, textBoxID)
        {
            document.getElementById(textBoxID).disabled = !bEnable
        }
    </script>

before closing the body, or to be invoked on DOM ready. In this way the code is being executed before even the checkbox and the text field exists.

By default the text input is enabled so you may need also to set the checkbox as checked.

Here is a working version:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
  <input type="text" id="txtBox" />
  <input type="checkbox" id="chkbox" onchange="document.getElementById('txtBox').disabled=!this.checked;" checked="checked" />
</body>
</html>

And a demo: http://jsbin.com/ulemim/2

1
  • hey, but if we remove the checked attribute(ie making unchecked by default) the code doesnt work for the 1st tym Jan 15, 2013 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.