'Enabling Disabling Text Fields using PHP when a radio button is clicked
I have 2 radio buttons(Enable/Disable) and 3 text boxes. I want to disable the 3 textboxes if disable radio button is clicked.
<Input type = 'Radio' Name ='target' value= 'r1'>Enable
<Input type = 'Radio' Name ='target' value= 'r2'>Disable
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
This change should happen as soon as I select one of the radio button. I am using PHP. TIA!
Solution 1:[1]
Although, using jQuery will make it easier, the following is one way to do it purely in JavaScript:
let textboxes = document.querySelectorAll('input[type=text]');
document.querySelectorAll('input[name=target]')
.forEach(function(radio) {
radio.addEventListener('change', function(e) {
let value = e.target.value;
if (value === 'r1') {
textboxes
.forEach(function(textbox) {
textbox.disabled = false;
});
} else if (value === 'r2') {
textboxes
.forEach(function(textbox) {
textbox.disabled = true;
});
}
});
});
<Input type='Radio' Name='target' value='r1'>Enable
<Input type='Radio' Name='target' value='r2'>Disable
<br><br>
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
It basically listens for the change event of the radio buttons and the loops through the text boxes to enable/disable them.
Solution 2:[2]
$('.radio').click(function(e) {
var val = $(this).val();
if(val=="r2") $('input[type="text"]').attr('disabled','disabled');
else $('input[type="text"]').removeAttr('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><Input class="radio" type = 'Radio' checked Name ='target' value= 'r1'>Enable </label>
<label><Input class="radio" type = 'Radio' Name ='target' value= 'r2'>Disable </label><br /><br />
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
Solution 3:[3]
Well, as you are using PHP, which is a server-side language, whenever you click radiobutton, refresh the page, and the radiobutton will get back to the unchecked state. So for this, you have to use JavaScript, and jquery is the best way to work with DOM elements. You need to add a few more lines of code. Don't forget to add jQuery in your HTML's ` tag.
<script type="text/javascript">
$(document).ready(function () {
$("#enable").click(function () {
$("#t1").attr("disabled", true);
});
$("#disable").click(function () {
$("#t1").attr("disabled", false);
});
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 31piy |
| Solution 2 | GYaN |
| Solution 3 | Karl Hill |
