2

Not work trim in JQuery. I can't see mistake:

<input type="text" name="name" class="inputsearch field" onchange="this.val($.trim(this.val()));"/>

Thanks for help!

4 Answers 4

6

this is a dom reference so it does not have .val() method, it has a property value which you can use.

<input type="text" name="name" class="inputsearch field" onchange="this.value = $.trim(this.value);"/>

Demo: Fiddle

or you can access the jQuery wrapper and use .val()

<input type="text" name="name" class="inputsearch field" onchange="$(this).val($.trim($(this).val()));"/>

But I would recommend against using inline event handlers and suggest adding handlers using script like

<input type="text" name="name" class="inputsearch field"/>

then

jQuery(function(){
    $('input[name="name"]').change(function(){
        this.value = $.trim(this.value);
    })
})

Demo: Fiddle

1
  • But inline event handlers in this situation i am can't use. I am everything use it. Commented Jan 27, 2014 at 11:01
2

You would not write inline jQuery code, also you can not call val() on this rather you need $(this). Pass the current object to javascript function using this. In javascript function you would jQuery method on object after converting DOM object to jQuery object

<input type="text" name="name" class="inputsearch field" onchange="someFun(this)"/>

function someFun(obj)
{
     $(obj).val($.trim(obj.val()));
}
1

this in your code is javascript and val() is jquery method

<input type="text" name="name" class="inputsearch field" onchange="$(this).val($.trim($(this).val()));"/>
1

try this

<input type="text" name="name" class="inputsearch field" onchange="$(this).val($.trim($(this).val()));"/>

Not the answer you're looking for? Browse other questions tagged or ask your own question.