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=''; }); });
val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .
jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With