Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Set Attribute value

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

like image 717
Jake Avatar asked Jan 05 '10 22:01

Jake


People also ask

How set value to data attribute in jQuery?

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.

What is ATTR jQuery?

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.

What does VAL () do in jQuery?

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 .

Which jQuery method has the purpose of getting or setting the value of an HTML attribute?

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.


1 Answers

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 
like image 102
Gabriele Petrioli Avatar answered Sep 25 '22 08:09

Gabriele Petrioli