How do you prevent spaces while pasting text into input field?

jquery

Solution

Bind the input event and replace the presence of spaces. For modern browsers, this covers both typing and pasting on an input field.

$('.no_space').on("input", function () {
    $(this).val($(this).val().replace(/ /g, ""));
});

See DEMO.

Problem

How to prevent spaces from being pasted into an input field? For example: I have two different `input` fields for first name and last name. I have disabled spaces from being typed into the input fields by using a simple jQuery, nevertheless, it seems that if I copied and pasted 'Tom Riddle' into either one of the input fields, the space between 'Tom' and 'Riddle' gets pasted into the input field as well. edit: As a first name of a person or a last name of a person will not contain any spaces, I need to disable. This is the `jQuery` which I use for disabling spaces from being typed :- ``` $(document).ready(function() { $('.no_space').keypress(function(e) { if(e.which === 32) { return false; } }); }); ```

Original source