Reputation: 53
Just wondering what is the difference between this.value
and $(this).val()
in jQuery? I realised when I console.log this.value
and console.log $(this).val()
, the results for each of them are different which meant that this.value
≠$(this).val()
Upvotes: 2
Views: 2995
Reputation: 54628
Just wondering what is the difference between this.value and $(this).val() in jQuery?
It depends on the context. When used correctly, they are exactly the same except for textareas:
At present, using .val() on elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR, however, carriage returns are preserved (or added by browsers which do not include them in the raw value).
I think this really is begs the question:
why does .val() exist if .value does the same thing.
This is because when you use jQuery to select an element $('#myinput')
, you are returned an array of HtmlElements, not a single element. In this case the code would have to index an element to get value using the property ('#myinput')[0].value = ('#myinput').val()
. So val()
is a nice shortcut, and provides a kind of error handling in certain cases.
When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null.
When used with a jQuery selector they definitely aren't the same thing.
Upvotes: 3
Reputation: 370729
When you're calling .val()
with no arguments, the result is almost always the same. You can see the source code here, search for val: function( value ) {
:
val: function( value ) {
var hooks, ret, valueIsFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return ret == null ? "" : ret;
}
return;
}
// other logic for when there are arguments
If the element definitely exists, and there are no valHooks
, then the only substantive line that will really do anything is
ret = elem.value;
which will then be returned at the end.
Note that you can call .val()
on a jQuery collection which contains no elements, in which case the empty string will be returned. (in contrast, trying to access the .value
of a non-existent element will throw an error)
The valHooks
are used to retrieve the value of certain elements which can't be accessed via .value
, like <select>
s, but this only has relevance for extremely ancient obsolete browsers - or if the script-writer has manually assigned to properties of $.valHooks
.
Upvotes: 4