John Ayers
John Ayers

Reputation: 519

Jquery trim this and set value

I'm getting a Invalid left-hand side in assignment error when running this jQuery command. Whats wrong with it and why isn't it working?

I'm trying to get a value from a field trim it then reset it.

$(this).val() = $.trim($(this).val());

Upvotes: 0

Views: 2122

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115232

You can do it with callback function of val()

$(this).val(function(i,v){ return $.trim(v); });

or using javascript

this.value = this.value.trim();

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

If you want to apply it to multiple items, with a single line of code, use val with a function:

$(':input').val(function(){ return $.trim($(this).val()) });

or

$(':input').val(function(i, val){ return $.trim(val) });

Note: this obviously also works for a single item.

e.g.

$(this).val(function(i, val){ return $.trim(val) });

Upvotes: 1

Frank van Wijk
Frank van Wijk

Reputation: 3252

The jQuery method val() is a setter and a getter. If you want to set the value, do:

$(this).val($.trim($(this).val()));

Next time please read the docs first.

Upvotes: 5

Related Questions