JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" maxlength="10" />
CSS
input {
display: block;
margin-bottom: 10px;
}
JavaScript
function insertAtCaretTrim(element, text) {
element[0].focus();
// Attempt to preserve edit history for undo.
var inserted = document.execCommand("insertText", false, $.trim(text));
// Fallback if execCommand is not supported.
if (!inserted) {
var caretPos = element[0].selectionStart;
var value = element.val();
// Get text before and after current selection.
var prefix = value.substring(0, caretPos);
var suffix = value.substring(element[0].selectionEnd, value.length);
// Overwrite selected text with pasted text and trim. Limit to maxlength.
element.val((prefix + $.trim(text) + suffix).substring(0, element.attr('maxlength')));
// Set the cursor position to the end of the paste.
caretPos += text.length;
element.focus();
element[0].setSelectionRange(caretPos, caretPos);
}
}
var $inputs = $("input");
$inputs.each(function () {
$(this).on('paste', function (evt) {
var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
var pastedData = clipboardData.getData('text/plain');
// Trim the data and set the value.
insertAtCaretTrim($(this), pastedData);
evt.preventDefault();
});
});