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!
Related
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.
I have an element that can exist as:
<input type="hidden" name="simple_search_criteria" id="simple_search_criteria" value="" />
or
<input type="hidden" name="simple_search_criteria" id="simple_search_criteria"/>
and my code needs to know whether the value exists and what the value is. I have code that works below, but feels kludgy since I'm doing two calls on the element, any suggestions on improving the code below?
if ($('#simple_search_criteria').attr('value') !== undefined) {
var searchCriteria = $('#simple_search_criteria').val();
// Do stuff with searchCriteria, even if it is an empty string
}
I like the code below but it doesn't work since .val() returns an empty string in both situations...
var searchCriteria = $('#simple_search_criteria').val();
if (searchCriteria) {
// do stuff with searchCriteria
}
Any improvements would be appreciated, I'm always trying to improve my js!
It would be faster to use regular JavaScript. Try hasAttribute and getElementById
var searchCriteria = document.getElementById('simple_search_criteria').hasAttribute('value');
I don't know if there is a jquery helper for checking the existance of an attribute but javascript has the method hasAttribute natively.
document.getElementById("simple_search_criteria").hasAttribute("value");
The idea is to check that val() returns anything and if so check if what is there is not empty.
To respond to a comment (that was deleted), typeof will return 'undefined' if for example the element (which corresponds here to $('#simple_search_criteria')) does not exist. Documentation for typeof can he also useful. You may have a look here.
var searchCriteria = $('#simple_search_criteria').val();
if (typeof(searchCriteria) !== 'undefined' and searchCriteria.length > 0) {
// do stuff with searchCriteria
}
An input element always has a value, even if its value attribute is omitted in the markup, which is why .val() doesn't distinguish between the presence of the attribute with an empty value, and the absence of the attribute. Critically, your form will submit with the same simple_search_criteria= (empty string) data in both cases, so the server receiving the form submission will not be able to distinguish the two. This is something you'll need to keep in mind when designing your form. If you want to omit this parameter you need to omit this particular input element altogether, not just its value attribute.
Nevertheless, if you want your application to behave based on the presence or absence of the attribute you need to check that directly. You can save some overhead by caching the selector in a separate variable:
var searchCriteriaInput = $('#simple_search_criteria');
if (searchCriteriaInput.attr('value') !== undefined) {
var searchCriteria = searchCriteriaInput.val();
// Do stuff with searchCriteria, even if it is an empty string
}
You can instead use the typeof attribute to distinguish between undefined and the empty string in this case:
typeof(document.getElementById("simple_search_criteria"))==='string';
More details here
I have a hidden element and within my jQuery:
<input type="hidden" id="1val" value="24">
var valID = $("#1val").attr("value");
However when I try to print valID it is always printed as undefined? What am I doing wrong?
Thanks
It's always safer to use the .prop() or .val() method to get the current value property:
var valID = $("#1val").val();
// or
var valID = $("#1val").prop("value");
As of jQuery version 1.9, the .attr() method will only get the element's attribute, which may not actually reflect the element's actual property.
According to the version 1.9 release notes, under .attr() versus .prop():
The value property versus attribute on input elements is another example of this ambiguity. The attribute generally reflects the value that was read from the HTML markup; the property reflects the current value. Since the .val() method is the recommended jQuery way to get or set the values of form elements, this confusion usually does not affect users.
However, when a selector like input[value=abc] is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.
Under the hood, as of version 1.9, the .attr() method will only return the current attribute of the element (and not the property). The attribute and the property may not actually be the same. For instance, if there was initially no attribute on the element, and then the value was programatically set using a method such as .val(), then the attribute wouldn't have changed meaning that .attr('value') would return undefined.
As stated above, use the .prop() or .val() method in order to get the element's current value property.
Use $('#input-id').val(); to get value of input.
One use case is in jQuery:
$select.append('<option value="">All</option>');
It looks like it actually adds the element in HTML:
<option value>All</option>
Instead, what I want is to append to the element so that it gives an empty string to value:
<option value="">All</option>
Why doesn't that happen?
It actually add the element in HTML
No, it doesn't.
It adds the element to the DOM, not to the HTML.
When you look at the DOM, using your browser's developer tools, it will displayed using HTML-like syntax. In this syntax, a value attribute where the value is an empty string will be rendered without the ="" portion. (It is looking like that part of the syntax is actually valid HTML, but I haven't found the part in the spec which allows it.)
If you were (to use Chrome as an example), you could right click on its parent element and pick "Edit as HTML" at which point you would see the ="" again.
If you were to submit the form containing the select element you would see that the data sent would be: select_name=. This shows that the value was correctly set to an empty string. If it had not worked you would have got select_name=All since the element's text is used as the value if no value is set.
Your question seems to indicate a degree of confusion as to the meaning of the syntax in question. Based on the fact that the occurrence of value in your tag lacks a ="", you're inferring that this represents an HTML "value" element - that's not the case. What's actually happening here has to do with the fact that there's multiple ways in which the value of an HTML attribute can be represented. Let's explore those formats, to better understand what you're seeing.
Valid formats for HTML Attributes
The most common way you'd represent, say, a value attribute would be with quotes, as follows:
value="something"
However, if you look at the section of the HTML5 spec regarding attributes, it's actually also valid to represent attribute values in four different ways:
empty attribute syntax
unquoted attribute-value syntax
single-quoted attribute-value syntax
double-quoted attribute-value syntax
The format that specifically speaks to your case is "empty attribute syntax". Reading further, the spec describes the Empty Attribute syntax as follows:
Just the attribute name. The value is implicitly the empty string.
There's also a slightly more detailed explanation on the historical HTML 5 reference for attributes:
Certain attributes may be specified by providing just the attribute
name, with no value.
In the following example, the disabled attribute is given with the
empty attribute syntax:
<input disabled>
Note that empty syntax is exactly equivalent to specifying the empty
string as the value for the attribute, as in the following example.
<input disabled="">
As you're seeing, this means that for an HTML element, when representing a property with no value, the ="" is optional. As such, some browsers will just display the property without that unnecessary markup. Whether the property is rendered as value or value="", any standards compliant browser will know that value is a property which holds a string, so it will therefore always return either that property's contents, if any, or at minimum an empty string in absence of explicit contents.
$select.append($('<option>', { value: "", text: "All" }));
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