Reputation: 1492
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?
Upvotes: 8
Views: 5698
Reputation: 1451
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);
});
Upvotes: 2
Reputation: 775
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>
Upvotes: 0
Reputation: 115222
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
Upvotes: 14