dopatraman
dopatraman

Reputation: 13908

Passing "this" into the $.trim() function

Jquery in Action has the following code:

$('#someField').val($.trim($('#someField').val()));

When I rewrite as follows though, the code does not work.

$('#someField').val($.trim($(this));

Can anyone help me understand why this does not work?

Upvotes: 4

Views: 198

Answers (6)

Stefan Kendall
Stefan Kendall

Reputation: 67832

When you execute that code, this refers to the owner of whatever function you're in.

$(this), then, will never resolve to text, where $('#someField').val() will.

Upvotes: 0

qwertymk
qwertymk

Reputation: 35284

You need to be in another function for the this keyword to change. For example:

$('div').slideToggle(1000, function() { // notice the function keyword
    // Now the this keyword has changed, notice the indentation due to the function
    $(this).css('border', '1px solid black'); // Here's how we use this
});

Of course the fact that this in the previous example changed to the object that we animated was something that jQuery did for us, it's not automatic. While it is possible for something like this to work:

$('#someField').val(function() { $.trim($(this).val()); } );

jQuery chooses not to let you pass a function as a parameter to the .val() method since it won't normally be used that way and therefore what you're trying doesn't work.

EDIT:

Now that I think about it, it wouldn't be to hard to implement:

var _val = $.fn.val;
$.fn.val = function(a) {
    return (!a || typeof a === 'string') ?
        _val.call(a) :
        _val.call(this, a.call( this.val() ));
}

Duck Punching by Paul Irish (read it!)

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385204

Two reasons:

  • trim takes a string, not a jQuery object. You'd need $(this).val() at least.

  • The selector is not encapsulating a function, so this actually doesn't get set to the object you selected. this is whatever it was anyway.

The best solution is this:

var $obj = $('#someField');
$obj.val($.trim($obj.val()); // trim object's value

Upvotes: 2

Mrchief
Mrchief

Reputation: 76218

$('#someField').val() retrieves the text of somefield, hence trim works as it is working on a string.

$(this) is just a jQuery object (this referring to the context in which it is called), hence trim has no meaning on it.

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

$.trim expects to receive a string as an argument. $(this) is not a string.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78540

When $.trim is hit, this is no longer the #someField element but rather, the DOMWindow. This is because $ resides in the DOMWindow and not your #someField element

Upvotes: -1

Related Questions