When I try to set a text input to blank (when clicked) using $(this).value=\"\"
, this does not work. I have to use $(this).val(\'\')
.
Why?
$(this).value
is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val()
.
Note that :
typeof $(this)
is JQuery object.
and
typeof $(this)[0]
is HTMLElement object
then :
if you want to apply .val()
on HTMLElement , you can add this extension .
HTMLElement.prototype.val=function(v){
if(typeof v!=='undefined'){this.value=v;return this;}
else{return this.value}
}
Then :
document.getElementById('myDiv').val() ==== $('#myDiv').val()
And
document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
العكس
INVERSE :Converselyو if you want to add value property to jQuery object , follow those steps :
Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .
Insert Line after L96 , add this code value:""
to init this new prop
Search on jQuery.fn.init
, it will be almost Line 2747
value
prop : (Before return statment add this.value=jQuery(selector).val()
)
You want:
this.value = ''; // straight JS, no jQuery
or
$(this).val(''); // jQuery
With $(this).value = ''
you're assigning an empty string as the value
property of the jQuery object that wraps this
-- not the value
of this
itself.
One thing you can do is this:
$(this)[0].value = "Something";
This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.