Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery function val() is not equivalent to "$(this).value="?

Tags:

jquery

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='';     }); }); 
like image 900
lkahtz Avatar asked Dec 24 '10 06:12

lkahtz


People also ask

What does VAL () do in jQuery?

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), .

How do I set the value of a element in jQuery?

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 value in JavaScript?

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.


1 Answers

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.

like image 195
Ken Redler Avatar answered Sep 23 '22 21:09

Ken Redler