I have following HTML with two elements having the same name
<input type="hidden" name= "chk0" value=""> <input type="checkbox" name="chk0" value="true" disabled>
Through JQuery, I want to set the enable the checkbox. So, I am using something like this:
$('#chk0').attr("disabled",false);
But this doesn't work. I assume JQuery is getting confused with two elements having the same identical name. Unfortunatel, I cannot avoid using two different names because, when the form is posted, I want all the checkboxes to get posted (not just the ones that are checked). Hence I have to use hidden element with the same name.. So, back to the question, how can I enable the checkbox through JQuery in the above scenario? Is there a "type" parameter for attr which distingues hidden from checkbox?
Thanks
To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined .
Using jQuery's .attr() method to get the value of an element's attribute has two main benefits: Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
Some things before the actual code..
the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..
so the code would be
$("input:checkbox[name='chk0']").removeAttr('disabled');
Bringing the answer up-to-date
You should use the .prop()
method (added since v1.6)
$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox
and
$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox
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