8

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?
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Scott B
  • 38,833
  • 65
  • 160
  • 266
  • Possible duplicate: http://stackoverflow.com/questions/686995/jquery-catch-paste-input – a'r Jul 07 '11 at 16:15

4 Answers4

17

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.

MacMac
  • 34,294
  • 55
  • 151
  • 222
4

check out this response Catch paste input

apparently you need to set a small settimeout to catch the pasted input value

this should do the trick:

("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value') = $.trim($(this).val());
    var el = $(this);
    setTimeout(function()
    {
        var text = $(el).val();
        alert($.trim(text)); //why no alert?
    }, 500);
});
Community
  • 1
  • 1
Christian Smorra
  • 1,756
  • 11
  • 13
3
$(this).val($(this).val().trim());
alert($(this).val());
Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
Espiral
  • 31
  • 1
1

I know this is a very old question but this is pretty obvious...

The only poblem with your code is with this line:

$(this).attr('value') = $.trim(this).val();

Which is incorrect in JavaScript. I think you meant this:

$(this).attr('value', $.trim(this).val());

And the resulting code works perfectly:

$("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value', $.trim(this).val());
    alert($(this).val()); 
});
jcarrenog
  • 199
  • 1
  • 3