Reputation: 1547
i am trying to create a form where a text field loads up disabled, and if the user wants to input into this field they have to click a check box. I have this at the moment.
However with what is below the text box loads up enabled and ticking the check box will disable it. How can this be modified so this is reversed. i.e. the text box is first disabled and clicking the check box enables it?
Javascript code
$(document).ready(function () {
$('#testcheckbox').change(function() {
$('#testtextfield').attr('disabled', this.checked);
});
});
HTML code
<input type="checkbox" id="testcheckbox" />
<input type="text" id="testtextfield" />
Thanks.
Upvotes: 1
Views: 2440
Reputation: 45
Pure JavaScript equivalent if you don't want to use jQuery.
<input type="text" id="inputbox" diasbled="disabled" />
var inputbox = document.getElementById('inputbox');
document.addEventListener('DOMContentLoaded',function(){
inputbox.removeAttribute('disabled');
});
Upvotes: 0
Reputation: 50905
Try using this setup:
<input type="checkbox" id="testcheckbox" />
<input type="text" id="testtextfield" disabled="disabled" />
$(document).ready(function () {
$('#testcheckbox').change(function() {
$('#testtextfield').prop('disabled', !this.checked);
});
});
In this case, the textbox is disabled
by default. Then, when clicking on the checkbox, the textbox is disabled based on its inverted checked
property, for the opposite behavior you wanted.
If you look at http://api.jquery.com/prop/ , you'll see that it is the jQuery method more accepted for changing elements' properties like "disabled", "readonly", "checked", etc. And a good discussion about the differences: .prop() vs .attr() . But it's really up to you if you need to be changing the attribute or property, as they have different meanings.
Upvotes: 5