I have an <input> element which is loaded with a default value. Later on, i change that value via jQuery's input.val("different value").
When I console.log() the element, I see this in firebug:
Object[input.cs_required.form-control.input-sm property value = "12/29/2014" attribute value = "12/02/2014"]
Why are there two different values assigned to the input?
What is the
difference between the property value and the attribute value?
Should
I be concerned?
Quick example of the difference:
jQuery('#something').val() changes the *.value property.
jQuery('#something').attr('value','neValue') changes the attribute on that component.
There is an important difference between the two. Take a look at this for more info.
What's the difference between jQuery .val() and .attr('value')?
The only thing you have to worry about is whether you are using/assigning/utilizing the correct item - property or attribute.
As you said, you are providing a default value via the value HTML attribute. That will be the initial value of the DOM element's value property. Changing the propery does not affect the attribute.
The value of HTML attributes is often used as initial value for the corresponding DOM property.
Related
I have a one span tag with data attribute, data-kr-id. On clicks of different items of the list, I update this span's data-kr-id attributes and it gets updated.
When for the first time I retrieve this(data-kr-id) value using jQuery's data method, I get the correct value. But from the subsequent time, I always get the same value as of the first time. But on using jQuery's attr function, I get the correct value. Can't figure out why.
CODE: Where I set the data-kr-id value:
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
CODE: Where I retrieve the values:
var topicId = $applozic(this).data("kr-id");
topicId = $applozic(this).attr("data-kr-id");
In the above code where I retrieve values, using data method gives me old value(the value of the first item I retrieved), but using attr method gives me correct value.
UPDATE :
As informed by everyone, I was setting the data attributes with attr method and retrieving the value with data method. After using data method for setting the attribute, When I was retrieving the values, I was getting a getting empty string. After digging a bit deeper, I realized there are two different versions of the jQuery are being used here.
Sorry for the incomplete information and late update.
You set value only using attr, Second time when you set data-kr-id value using attr then data value remains same, so need to set value with data also
// With Attr
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
// With Data
$_applozicWtLauncherBtn.data('kr-id', seller.UserId);
Actually jquery's .data() fetches value from the property (same as .prop()) not from attributes. Main difference is .attr() fetches data from HTML tag which you can see it will reflect on your HTML when you update it with .attr(). But when you use .prop() or .data() it will not reflect in HTML tag but it will update value in it's property for that HTML tag as per the DOM tree.
You'll find out more about difference property and attribute from here.
Initially this property will set when your element is created. So for the first time your .data() and .attr() will work fine. When you update value from .attr() it will manipulate DOM but property will be remain same.
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.
Inside a javascript function Im accessing a text box with a value of 'c29TMlzE4vmFlJHieICpso_u04oa'. Below is the javascript function i'm using.
function test(){
var txt = document.getElementsByName("consumerKey");
alert(txt.item[0].getPropertyValue);
}
The alert shows as 'undefined'. In console I'm getting below as NodeList value of the txt.
NodeList[input#consumerKey property value ="c29TMlzE4vmFlJHieICpso_u04oa" attribute value = "null"]
How can I extract 'c29TMlzE4vmFlJHieICpso_u04oa' from the nodelist.
Thanks
item is a method, so you call it with a parameter:
txt.item(0)
Or you could access it as
txt[0]
getPropertyValue is for getting CSS property values from a style object, and is not relevant here. You simply want to access the value member of the input element:
txt.item(0).value
txt[0].value
However, there is really no need to use name attributes, except in special situations such as to group radio buttons. You're better off using IDs and getElementById. Then you don't have to worry about taking the first item.
I used to think that changing an HTML element's attribute value will cause the property value to change, but changing the property value will NOT cause the attribute to change, because the attribute is like a blueprint as described by the HTML, and the property is the "live data".
But it turned out that, using plain JavaScript, if we change the property value, the attribute value is changed too. Although in general, property value can be any data type, such as string, boolean, or object, while an attribute value should only be a string. And the other difference is that attribute names are case-insensitive, but property names are case-sensitive. (as described in JavaScript Definitive Guide 6th edition, p. 375 - 376).
I tried it in:
http://jsfiddle.net/5nBM3/1/
and http://jsfiddle.net/5nBM3/2/ where it sets the property value, and in http://jsfiddle.net/5nBM3/3/ where it sets the attribute value.
If we sets the attribute value by using:
el.setAttribute("src", "http://i.imgur.com/4rE6FHV.gif");
then clearly, inside of setAttribute(), it can adjust the property value as well. But if we set the property value by using:
el.src = "http://i.imgur.com/4rE6FHV.gif";
so if we consider it just like obj.x = 1, then it should not cause anything else to change. How does the line above cause the attribute value to change as well? Is it by
the object setter and getter function as in ECMA-5 (and in some ECMA-3 implementation) similar to the situation that if an object only has property x and y, we can define a setter and getter r for the radius, and use it as a = obj.r or obj.r = 3, so that getting the radius will invoke a function to calculate it using x and y, and setting r will invoke a function to adjust the values of x and y according to the new r, or
some observer model so that attribute observes the changes of property value, and property observes the change of attribute value, or
we can consider it just a black box or "magic", that the client-side JavaScript always maintain the value equivalence between a property and an attribute?
I'm looking to get the used css values of all DOM elements on a page. When I say "used values" I'm referring to the definition as specified in the W3C specification:
6.1.3 Used values
Computed values are processed as far as possible without formatting the document. Some values, however, can only be determined when the document is being laid out. For example, if the width of an element is set to be a certain percentage of its containing block, the width cannot be determined until the width of the containing block has been determined. The used value is the result of taking the computed value and resolving any remaining dependencies into an absolute value.
These should be the final values computed with respect to the actual page layout. Mozilla's docs claim that you can use window.getComputedStyle to get the used values, but this does not make sense to me because computed values are different from used values (and I want used values). Even if these are the used values, I'm not sure if this only works in Firefox or not. Is there a way to reliably get used values in all browsers?
Note: The world has moved on since the question was asked and answered. There are now more layers of values than there used to be: declared, cascaded, specified, computed, resolved, used, and actual. getComputedStyle returns resolved values (which are either computed or used depending on the property). Here are the layers:
From CSS Cascading and Inheritance Level 4:
Once a user agent has parsed a document and constructed a document tree, it must assign, to every element in the tree, and correspondingly to every box in the formatting structure, a value to every property that applies to the target media type.
The final value of a CSS property for a given element or box is the result of a multi-step calculation:
First, all the declared values applied to an element are collected,
for each property on each element.
There may be zero or many declared values applied to the element.
Cascading yields the cascaded value.
There is at most one cascaded value per property per element.
Defaulting yields the specified value.
Every element has exactly one specified value per property.
Resolving value dependencies yields the computed value.
Every element has exactly one computed value per property.
Formatting the document yields the used value.
An element only has a used value for a given property
if that property applies to the element.
Finally, the used value is transformed to the actual value based on constraints of the display environment.
As with the used value, there may or may not be an actual value for a given property on an element.
Then, the CSS Object Model defines resolved values:
getComputedStyle() was historically defined to return the "computed value" of an element or pseudo-element. However, the concept of "computed value" changed between revisions of CSS while the implementation of getComputedStyle() had to remain the same for compatibility with deployed scripts. To address this issue this specification introduces the concept of a resolved value.
The resolved value for a given longhand property can be determined as follows:
...which is followed by a list of properties (specific ones and categories) saying whether the resolved value is the computed or used value.
With that backdrop:
getComputedStyle works on all major modern browsers. Earlier versions of IE provide a near-equivalent in the form of currentStyle.
getComputedStyle returns resolved values, which for any given property is either the computed value or the used value, with the CSSOM spec defining clearly what properties get returned with which kind of value under which circumstances. I don't see anything in CSSC&I4 or CSSOM defining a way to access used values in cases where the resolved value isn't the used value, or a way to access actual values, and gsnedders says they have checked with the working group and confirmed there isn't a way to get used values, at least not yet.
Resolved values are probably good enough for what you need. For instance, the following example shows 207.5px or similar , not 50%. That's the resolved value, which is also the used value in this particular case (because I used width on an element where the display isn't none or contents), but possibly not the actual value, depending on whether subpixel rendering is feasible and appropriate in this case.
(function() {
var target = document.getElementById("target");
var style = window.getComputedStyle(target);
display("computed width = " + style.width);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
<div id="target" style="display: inline-block; width: 50%">x</div>
You could use jQuery or another preferred library in most cases.
For instance, your question title has font-size:100% applied to it which can be retrieved w/firebug. But with jQuery api you can retrieve the value used like so:
$('#question-header .question-hyperlink').css('font-size');//run in console
//or enter this in the url bar
//javascript:alert($('#question-header .question-hyperlink').css('font-size'));
//returns "23.06px"
NB the library is included on this page, but it would be fairly trivial to create a bookmarklet that includes jQuery and polls the necessary properties.