0

I have a check box and 3 textboxes, what i want is to disable all 3 textboxes when check box is checked. For that i have done this code but not working.

<tr>
<td><?php echo "Modify Default Package Dimensions:"; ?></td>
<td><input type="checkbox" name="Modify_Default_Dimensions" value="1" onclick="document.getElementsByClassName('hide_textbox').disabled=this.checked;"></td>
</tr>

<td><?php echo "Depth"; ?></td>
<td><input type="text" class="hide_textbox" name="dhl_product_depth" value="<?php echo $product_depth ?>" /> cm</td>
</tr>
<tr>
<td><?php echo "Width"; ?></td>
<td><input type="text" class="hide_textbox" name="dhl_product_width" value="<?php echo $product_width ?>" /> cm</td></tr>
<tr>
<td><?php echo "Height"; ?></td>
<td><input type="text" class="hide_textbox" name="dhl_product_height" value="<?php echo $product_height ?>" /> cm</td>
</tr>
Ammar Ul Hassan
  • 826
  • 1
  • 18
  • 48
  • Try the `setAttribute()` function in javascript, for example see this link: http://www.w3schools.com/jsref/met_element_setattribute.asp – node_modules Mar 29 '16 at 10:08
  • @C0dekid.php whats wrong with mine? and why its not working? – Ammar Ul Hassan Mar 29 '16 at 10:10
  • You used the `this` property, but that only handles the current object/input. And because there are three inputs with the same class you can't directly change this all – node_modules Mar 29 '16 at 10:13
  • @C0dekid.php — No, the use of `this` is correct. It is trying to read the value from *one* checkbox (which it is doing correctly) and copy it to three others (which is where the problem is). – Quentin Mar 29 '16 at 10:28

1 Answers1

0

getElementsByClassName returns a node list (something like an array but without the methods) and you have to loop through the array to modify each member with that specified class.

For readability, modify your checkbox to call a function when clicked:

<input type="checkbox" name="Modify_Default_Dimensions" value="1" onclick="checkboxChecked(this);"></td>

And define the function:

function checkboxChecked(clickedBox) {
    var hide_textbox = document.getElementsByClassName('hide_textbox');
    for(var i = 0; i < hide_textbox.length; i++) {
        hide_textbox[i].disabled = clickedBox.checked;
    }
}


EDIT: If you want your textboxes disabled by default and checking the checkbox will enable them, firstly add this to disable all text box on page load:
var textboxes = document.getElementsByClassName('hide_textbox');
for(var b = 0; b < textboxes.length; b++) {
    textboxes[b].disabled = true;
}

And then you can modify your function (note that i don't define hide_textbox this time).

function checkboxChecked(clickedBox) {
    for(var i = 0; i < textboxes.length; i++) {
        textboxes[i].disabled = !clickedBox.checked; // if checked, this will enable it
    }
}
chris97ong
  • 6,870
  • 7
  • 32
  • 52