Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a boolean attribute with jquery

Tags:

jquery

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">.

like image 592
Chad Kapatch Avatar asked Oct 17 '12 18:10

Chad Kapatch


People also ask

How do you set a Boolean attribute?

To set the value of a Boolean attribute, such as disabled , you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true .

How do you assign a Boolean value in HTML?

Use the reserved keywords true or false to assign a boolean value to a variable. The same logic applies when creating a boolean in JSON. let example1a = true; let example1b = false; Never explicitly specify a boolean value as a string or as an object.

How do you declare a Boolean variable in JavaScript?

JavaScript provides the Boolean() function that converts other types to a boolean type. The value specified as the first parameter will be converted to a boolean value. The Boolean() will return true for any non-empty, non-zero, object, or array.

How add data attribute in jQuery?

Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.


1 Answers

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

like image 189
Selvakumar Arumugam Avatar answered Oct 05 '22 08:10

Selvakumar Arumugam