15

I understand that jquery will allow you to modify attributes with the .attr() method. There are basically two methods:

$('#element').attr('attribute', 'value') // sets the attribute
var attribute = $('#element').attr('attribute') // gets the attribute

My question is, how do you set a boolean attribute such as 'checked' on a checkbox or 'multiple' on a select tag?

I've tried doing the following without success:

$('#element').attr('attribute', true)
$('#element').attr('attribute', '')

All of these add the attribute but usually like this <tag attribute="attribute">.

3 Answers 3

23

Try using .prop to deal with boolean that is for supported attributes like selected/disabled/checked e.t.c

$('#element').prop('attribute', true);

from jQuery docs, (an example)

elem.checked returns true (Boolean) Will change with checkbox state

$(elem).prop("checked") returns true (Boolean) Will change with checkbox state

elem.getAttribute("checked") returns "checked" (String) Initial state of the checkbox; does not change

$(elem).attr("checked")(1.6) returns "checked" (String) Initial state of the checkbox; does not change

$(elem).attr("checked")(1.6.1+) returns "checked" (String) Will change with checkbox state

$(elem).attr("checked")(pre-1.6) returns true (Boolean) Changed with checkbox state

Sign up to request clarification or add additional context in comments.

1 Comment

prop() sets the property, attr() sets the attribute. It is not always correct to "just use prop() instead".
1

I use this method in jQuery

jQuery('option').attr("selected", "");

or in JavaScript:

document.querySelector("option").setAttribute("selected", "");

It's just you need to pass an empty string to just set boolean attribute.

Comments

-1

HTML attributes are always string values. If you indeed want to set something other than a string, then please consider using jQuery.data()

2 Comments

Not true in HTML5: dev.w3.org/html5/spec/…
You are right, I shouldn't have made that assumption... apologies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.