Reputation: 11
I want to be able to disable and enable a textbox using a checkbox. I have this code, but the problem is, when I checked the checkbox the textbox gets enabled. However, when I unchecked it, it doesn't get disabled again. could anyone tell me what is wrong in this code?
function toggleDIOthers(opt) {
if (opt == 'DIOthers')
document.getElementById('DIOthers').disabled = false;
else
document.getElementById('DIOthers').disabled = true;
}
<div class="col-xs-4">
<label class="checkbox-inline">
<input type="checkbox" value="DIOthers" onClick="toggleDIOthers('DIOthers')" name="types_house[]"
{if in_array('DIOthers', $data.house)}
checked
{/if}
>Others:</label>
<input type="text" id="DIOthers" disabled class="form-control" name="types_house_others" required value="{$data['houseOthers']}">
</div>
If the checkbox is checked i want to make the textbox required.
Upvotes: 0
Views: 765
Reputation: 31815
You can pass the element as parameter and check its value like this:
function toggleDIOthers(opt, elt) {
if (opt == 'DIOthers'){
document.getElementById('DIOthers').disabled = !elt.checked;
}
}
<div class="col-xs-4">
<label class="checkbox-inline">
<input type="checkbox" value="DIOthers" onClick="toggleDIOthers('DIOthers', this)" name="types_house[]"
{if in_array('DIOthers', $data.house)}
checked
{/if}
>Others:</label>
<input type="text" id="DIOthers" disabled class="form-control" name="types_house_others" required value="{$data['houseOthers']}">
</div>
Upvotes: 1
Reputation: 911
You can change your function to toggle the disable attribute by the oposite of what it currently is.
function toggleDIOthers() {
var textbox = document.getElementById('DIOthers');
textbox.disabled = !textbox.disabled;
}
<div class="col-xs-4">
<label class="checkbox-inline">
<input type="checkbox" value="DIOthers" onClick="toggleDIOthers()" name="types_house[]"
{if in_array('DIOthers', $data.house)}
checked
{/if}
>Others:</label>
<input type="text" id="DIOthers" disabled class="form-control" name="types_house_others" required value="{$data['houseOthers']}">
</div>
Upvotes: 1