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">
.
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With