Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white spaces after paste with jQuery

Tags:

jquery

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?

like image 885
Dave Avatar asked Sep 27 '15 16:09

Dave


People also ask

How to trim whitespace jQuery?

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.

How to remove white space JavaScript?

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.).


1 Answers

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

like image 65
Pranav C Balan Avatar answered Oct 06 '22 01:10

Pranav C Balan