8

I tried it (jsfiddle), but it's not working.

How can you see the alert is empty. It's like .val() function starts before the string is copied.

$(document).on('paste', '#pasteIt', function(){
    alert($("#pasteIt").val());
    var withoutSpaces = $("#pasteIt").val();
    withoutSpaces = withoutSpaces.replace(/\s+/g, '');
    $("#pasteIt").text(withoutSpaces);
});

Why?

Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46
Dave
  • 1,428
  • 4
  • 31
  • 49

3 Answers3

14

Get clipboard data

$(document).on('paste', '#pasteIt', function(e) {
  e.preventDefault();
  // prevent copying action
  alert(e.originalEvent.clipboardData.getData('Text'));
  var withoutSpaces = e.originalEvent.clipboardData.getData('Text');
  withoutSpaces = withoutSpaces.replace(/\s+/g, '');
  $(this).val(withoutSpaces);
  // you need to use val() not text()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="pasteIt" placeholder="Paste something here">

Ref : https://forum.jquery.com/topic/paste-event-get-the-value-of-the-paste#14737000004101955

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • It works! Can you explain me what `e.preventDefault(); alert(e.originalEvent.clipboardData.getData('Text'));` do? Thank you! – Dave Sep 27 '15 at 16:11
  • `e.preventDefault(); ` is for avoiding the default action, that copying content to the input box. We don't need to perform, instead we need to paste the space removed value – Pranav C Balan Sep 27 '15 at 16:13
  • `e.originalEvent.clipboardData.getData('Text')` is for getting clipboard content – Pranav C Balan Sep 27 '15 at 16:14
2

Use setTimeout, this delays the check so the value is retrieved. Check it out here.

$(document).on('paste', '#pasteIt', function () {
    setTimeout(function () {
        alert($("#pasteIt").val());
        var withoutSpaces = $("#pasteIt").val();
        withoutSpaces = withoutSpaces.replace(/\s+/g, '');
        $("#pasteIt").val(withoutSpaces);
    }, 1);
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
TheOnlyError
  • 1,441
  • 12
  • 19
0

So, you want this:

$(document).on('paste', '#pasteIt', function(e) {
  window.setTimeout(function() {
    var withoutSpaces = $("#pasteIt").val();
    withoutSpaces = withoutSpaces.replace(/\s+/g, '');
    $("#pasteIt").val(withoutSpaces);
  }, 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<span>Enter: </span>
<input id="pasteIt">

</html>
Universal Electricity
  • 775
  • 1
  • 12
  • 26