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? What is the difference? What is the mechanism behind the val
function in jQuery?
$(document).ready(function() {
$('#user_name').focus(function(){
$(this).val('');
});
});
// error code: not working...
$(document).ready(function() {
$('#user_name').focus(function(){
$(this).value='';
});
});
This question is related to
jquery
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.
$(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()
)
Source: Stackoverflow.com