Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attribute in jQuery

Tags:

html

jquery

tags

How can I add an attribute into specific HTML tags in jQuery?

For example, like this simple HTML:

<input id="someid" /> 

Then adding an attribute disabled="true" like this:

<input id="someid" disabled="true" /> 
like image 234
Yuda Prawira Avatar asked May 13 '11 17:05

Yuda Prawira


People also ask

How set 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.

How we can use different attribute of HTML in jQuery?

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. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

How get data attribute in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

You can add attributes using attr like so:

$('#someid').attr('name', 'value'); 

However, for DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

$('#someid').prop('disabled', true); 
like image 74
Paul Rosania Avatar answered Oct 12 '22 17:10

Paul Rosania


best solution: from jQuery v1.6 you can use prop() to add a property

$('#someid').prop('disabled', true); 

to remove it, use removeProp()

$('#someid').removeProp('disabled'); 

Reference

Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

like image 26
diEcho Avatar answered Oct 12 '22 17:10

diEcho