checked = "checked" vs checked = true - javascript

What is the difference between the below two usages?
document.getElementById('myRadio').checked = "checked";
and
document.getElementById('myRadio').checked = true;
For me, both are behaving the same way. But, I am just curious to know why there exist two methods to do the same.
Which one will be the ideal usage? I need to support IE7 and higher versions.

document.getElementById('myRadio').checked is a boolean value. It should be true or false
document.getElementById('myRadio').checked = "checked"; casts the string to a boolean, which is true.
document.getElementById('myRadio').checked = true; just assigns true without casting.
Use true as it is marginally more efficient and is more intention revealing to maintainers.

The element has both an attribute and a property named checked. The property determines the current state.
The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.
If there is no value for the attribute in the markup, the attribute becomes null, but the property is always either true or false, so it becomes false.
When you set the property, you should use a boolean value:
document.getElementById('myRadio').checked = true;
If you set the attribute, you use a string:
document.getElementById('myRadio').setAttribute('checked', 'checked');
Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.
Note also that whatever value you set the attribute to, the property becomes true. Even if you use an empty string or null, setting the attribute means that it's checked. Use removeAttribute to uncheck the element using the attribute:
document.getElementById('myRadio').removeAttribute('checked');

The original checked attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.
This, however is not valid for XHTML that followed HTML 4.
The standard proposed to use checked="checked" as a condition for true - so both ways you posted end up doing the same thing.
It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).

document.getElementById('myRadio') returns you the DOM element, i'll reference it as elem in this answer.
elem.checked accesses the property named checked of the DOM element. This property is always a boolean.
When writing HTML you use checked="checked" in XHTML; in HTML you can simply use checked. When setting the attribute (this is done via .setAttribute('checked', 'checked')) you need to provide a value since some browsers consider an empty value being non-existent.
However, since you have the DOM element you have no reason to set the attribute since you can simply use the - much more comfortable - boolean property for it. Since non-empty strings are considered true in a boolean context, setting elem.checked to 'checked' or anything else that is not a falsy value (even 'false' or '0') will check the checkbox. There is not reason not to use true and false though so you should stick with the proper values.

checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
w3c

Related

Vue.js, how to pass boolean on input value

I want to pass boolean value on input, like
v-bind:value="false"
but it doesn't work, on true it work but it doesn't work on false, what could be the cause ?
Depending on your use case, you can either use "" (empty string) instead of false, or reorganize your component that uses this property. Quoting the docs:
Boolean attributes are attributes that can indicate true / false
values by its presence on an element. For example, disabled is one of
the most commonly used boolean attributes.
v-bind works a bit differently in this case:
<button :disabled="isButtonDisabled">Button</button>
The disabled attribute will be included if isButtonDisabled has a truthy value. It will also be included if the value is an empty string, maintaining
consistency with <button disabled="">.
For other falsy values the attribute will be omitted.

How to check if an attribute is a Boolean attribute?

Is there any way to check if some HTML attribute are Boolean? for example:
<input type="text" name="input" disabled=""/>
Here the disabled attribute is Boolean, I have some code and I need check before setting value whether that attribute is Boolean or not.
Why I need this?
As mentioned here we can have either "" or property name itself as the valid value not true or false.
There's basically no distinction on the level of HTML. If the attribute is simply the name without value, e.g. <input disabled>, that's a sure sign that it's a boolean attribute. However, if it's using the name="value" notation, then there's no way to distinguish it. Is class="class" a boolean attribute? No, it's a classList with one entry "class". How about foo=""? Well, it's either a boolean attribute opting for the empty-value notation, or it's an attribute with no value set.
Only the interpreter assigns boolean-ness to an attribute; i.e. while parsing the HTML into a DOM, the interpreter sets DOM attributes like this, roughly speaking:
domElement.disabled = htmlElement.hasAttribute('disabled');
If you want to know what HTML elements are booleans, you need to do the same thing an interpreter does: keep a list of DOM elements whose attributes have types and interpret the HTML according to that specification.
To solve this issue, you have the typeof operand in the following way:
var check_input = document.getElementById("check-input");
if(typeof(check_input.disabled) === "boolean"){
alert('Yes');
}
Here is a JSfiddle with the complete code. I hope that my answer can help you!

Jquery Issues with IE8 and Android

Having an issue with the following code on IE8 and some android versions. The variable "method" is always unset throwing the alert even when the object it refers to is checked. This works in most every other browser except IE8 and possibly IE9, as well as some android OS's (haven't nailed down exactly which ones).
$(document).ready(function() {
$('#choose_shipper').click(function(){
var method = $('#fedex_method:checked').val();
if (!method){
alert('Please select a shipping option');
}else{
DO SOMETHING ELSE HERE
}
});
});
EDIT
Simple answer, stupid habit... I was using multiple instances of the same id... Older browsers don't like that and treat all duplicate instances like they do not exist. SO! Changing "fedex_method" from an ID to a CLASS solved all the problems! My BAD!
To evaluate a single checkbox, try this instead
var method = $("#fedex_method").prop("checked");
To evaluate multiple checkboxes, something like
var method = $("#fedex_method:checked").length;
Or (since you should not have multiple checkboxes with the same id):
var method = $("input:checkbox[name=fedex_method]:checked").length;
Per the jquery documentation:
According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false". This is true of all boolean attributes.
Nevertheless, 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. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )

jQuery MultiSelect Library Uses Incorrect Method to Handle "Select All"?

I'm trying to update a large web application that uses an extended version of Cory S.N. LaViska's jQuery.multiSelect plugin.
I updated to the latest code and it fixed a problem I was encountering. However, it introduced a new problem: Checking the Select All option now unchecks everything instead of checking it.
I'm not super advanced in JavaScript but have isolated the problem to the following code:
currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
if ($(this).attr('checked') == true)
$(this).parent().parent().find('INPUT:checkbox').attr('checked', true).parent().addClass('checked');
else
$(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
});
The problem is that $(this).attr('checked') returns "checked". And so $(this).attr('checked') == true will always be false. And the code never detects that this option is, in fact, checked!
Okay, so I understand the problem. But why would it ever be written this way, and what is the most reliable way to fix this? I'd be interested to know how a JavaScript/jQuery expert would address this.
checked is a property, you should use prop method, when a boolean attribute like disabled or checked is set to an element, the value is mapped to the relevant DOM property of the element(browser do this), as of jQuery 1.6 for modifying properties, prop method should be used instead of attr.
So you code should looks like this
currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
if ($(this).is(':checked'))
$(this).parent().parent().find('INPUT:checkbox').prop('checked', true).parent().addClass('checked');
else
$(this).parent().parent().find('INPUT:checkbox').prop('checked', false).parent().removeClass('checked');
});
Better if you use .is(":checked") for checking whether the checkbox is checked or not. But use prop to set the checked property of checkbox.
Rather than using $(this).attr('checked') == true which will return a string try $(this).prop('checked') == true
$.prop() will return boolean true when the element is checked or boolean false when it is not.
A little extra information on $.attr() is it returns the contents of the attribute. So if your html is:
<input id="elem" type="checkbox" checked="checked" />
Then $('#elem').attr("checked") is only going to return the string inside that attribute of the selected element.
If you really wanted to use $.attr() you could do this.
if ($(elem).attr("checked") != '') { ... }

hasAttribute should return true even when the attribute is not explicitly specified, but doesn't

From W3C - hasAttribute - Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.
Now, all elements have a default class attribute as an empty string as mentioned here
So, if I apply hasAttribute('class') or hasAttribute('className') on an element on which I haven't explicitly specified the class attribute, it should even then return true, but it doesn't in Firefox and Chrome. Why is this happening ?
This is happening because of:
"However, empty default attributes do not appear in the DOM tree — only those attributes which have an actual value (either a specific default value in the DTD, or an explicit value) appear in the DOM; this is referred to as having an effective value. "
you can read it here

Categories