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?
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With