Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to trim() a text input field's value attribute?

In this jQuery, I'm able to bind the paste event to validate the form field, but my method inside the function is apparently wrong. I'm not getting an alert at all.

I just want to trim the text that's input and return that as the value of the form input text field #adsense_client_id.

$("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value') = $.trim(this).val();
    alert($(this).val()); //why no alert?
});
like image 817
Scott B Avatar asked Jul 07 '11 16:07

Scott B


1 Answers

The $.trim is a function which needs a variable/string inside it, since you did not wrap $(this).val() with $.trim in order for it to work.

As you need a timeout for the paste to be caught, do it like this:

$("#adsense_client_id").bind('paste', function(e) {
    var clientId = $(this);
    setTimeout(function(){
        clientId.val($.trim(clientId.val()));
        alert(clientId.val());
    });
});

Demo.

like image 120
MacMac Avatar answered Oct 26 '22 17:10

MacMac