Using Javascipt to disable multiple HTML Text fields with a HTML checkbox

Posted by Shek on October 16, 2011 under JavaScript | Be the First to Comment | Total View: 12,574 views

In this post, I am going to show by checking a checkbox to disable multiple HTML text field elements


The aim is by checking the checkbox, the 2 textfields will be disabled:

First we created 1 checkbox and 2 text fields:

1
2
3
<input type="checkbox" id="checkboxA"> click to disable<br>
<input type="text" id="textbox_A"> 
<input type="text" id="textbox_B">

Remember to insert an id attribute for all of the elements for identification of the Javascript function.

Then we create the Javascript function for disabling the 2 Text fields with the checkbox, and the Javascript function will be placed in the section:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript"> 
function disablefields(){ 
if (document.getElementById('checkboxA').checked == 1){ 
document.getElementById('textbox_A').disabled='disabled'; 
document.getElementById('textbox_A').value='disabled';
document.getElementById('textbox_B').disabled='disabled'; 
document.getElementById('textbox_B').value='disabled';
}else{ 
document.getElementById('textbox_A').disabled=''; 
document.getElementById('textbox_A').value='Allowed'; 
document.getElementById('textbox_B').disabled=''; 
document.getElementById('textbox_B').value='Allowed'; 
} 
} 
</script>

The Javascript function: when the checkbox with ID “checkboxA” is checked, the 2 text fields with ID “textbox_A” and “textbox_B” will be disabled and the text “disabled” will show up in the text fields.

At last, we insert the Javascript function into the checkbox’s code, so that when the checkbox is checked, the function will run:

1
<input type="checkbox" id="checkboxA" onclick="disablefields();"> click to disable<br>

All together we have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html> 
<head> 
<script type="text/javascript"> 
function disablefields(){ 
if (document.getElementById('checkboxA').checked == 1){ 
document.getElementById('textbox_A').disabled='disabled'; 
document.getElementById('textbox_A').value='disabled';
document.getElementById('textbox_B').disabled='disabled'; 
document.getElementById('textbox_B').value='disabled';
}else{ 
document.getElementById('textbox_A').disabled=''; 
document.getElementById('textbox_A').value='Allowed'; 
document.getElementById('textbox_B').disabled=''; 
document.getElementById('textbox_B').value='Allowed'; 
} 
} 
</script> 
</head> 
<body> 
<input type="checkbox" id="checkboxA" onclick="disablefields();"> click to disable<br>
<input name="atext1" type="text" id="textbox_A"> 
<input name="atext2" type="text" id="textbox_B"> 
</body> 
</html>

Here is a demo:
click to disable

To use radio button instead, please check: Using JavaScript to disable HTML textfield by clicking radio button

Not what you want? Try a Search

Add A Comment

*