Basically I'm trying to set the disabled attribute to a select node when the checkbox labeled as Section is not checked, if it is checked it should remove the attribute.
HTML:
<label>
<input type="radio" name="table" value="main_categories" checked>
Section</label>
<label>
<input type="radio" name="table" id="subcat" value="sub_categories">
Catégorie</label>
<select id="selectsec">
<option value="1">Test</option>
</select>
jQuery:
$(document).ready(function() {
$('#subcat').change(function(){
if (!$('#subcat').is(":checked")) {
$('#selectsec').attr('disabled','disabled');
}
else {
$('#selectsec').removeAttr('disabled');
}
});
});
For some reason this isn't working :(
Your event won't fire on de-selection, you need to apply the event to all of your radio buttons (we can use your name
attribute):
DEMO
$('input:radio[name=table]').change(function() {
if (!$('#subcat').is(":checked")) {
$('#selectsec').attr('disabled','disabled');
}
else {
$('#selectsec').removeAttr('disabled');
}
});
$('input').click(function() {
if($('#subcat').is(':checked')) {
$('#selectsec').attr('disabled','disabled');
}
else {
$('#selectsec').removeAttr('disabled');
}
});
DEMO
EDIT: It also will work if you selected an different radio button on your page. Put your radio buttons into a div and change
$('input').click(function()
to
$('#idOfyouDiv').click(function()
The problem is that the change
event doesn't fire on the un-checking of a radio input; therefore you have to bind the change
event-handler to the group of <input />
elements and check whether this
has the id
of the element you're looking to check, for example:
$(document).ready(function() {
// binding the change event-handler to all <input> elements
// whose type is 'radio' and whose name is 'table':
$('input[type=radio][name=table]').on('change', function() {
// this will be the <input> that *is* checked, so
// we test whether subcat is checked by checking the id
// of this changed <input> element:
var subcatChecked = this.id === 'subcat';
// setting the disabled property of the <select> element
// to true (when subcat is not checked) or false (when
// subcat is checked):
$('#selectsec').prop('disabled', !subcatChecked);
});
// triggering the change event-handler on page-load/document-ready:
}).filter('#subcat').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="table" value="main_categories" checked>Section
</label>
<label>
<input type="radio" name="table" id="subcat" value="sub_categories">Catégorie
</label>
<select id="selectsec">
<option value="1">Test</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With