jQuery: Adding two attributes via the .attr(); method
Should work:
.attr({
target:"nw",
title:"Opens in a new window",
"data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});
Note:
" When setting multiple attributes, the quotes around attribute names are optional.
WARNING: When setting the 'class' attribute, you must always use quotes!
From the jQuery documentation (Sep 2016) for .attr:
Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.
Edit:
For future reference...
To get a single attribute you would use
var strAttribute = $(".something").attr("title");
To set a single attribute you would use
$(".something").attr("title","Test");
To set multiple attributes you need to wrap everything in { ... }
$(".something").attr( { title:"Test", alt:"Test2" } );
Edit - If you're trying to get/set the 'checked' attribute from a checkbox...
You will need to use prop()
as of jQuery 1.6+
the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does
So to get the checked status of a checkbox, you should use:
$('#checkbox1').prop('checked'); // Returns true/false
Or to set the checkbox as checked or unchecked you should use:
$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
If you what to add bootstrap attributes in anchor tag dynamically than this will helps you lot
$(".dropdown a").attr({
class: "dropdown-toggle",
'data-toggle': "dropdown",
role: "button",
'aria-haspopup': "true",
'aria-expanded': "true"
});
Something like this:
$(myObj).attr({"data-test-1": num1, "data-test-2": num2});