[英]How can i disable/remove white spaces only at the beginning of text inside an input field when someone paste text using javascript or jquery?
我有一個輸入字段,並且我正在使用以下代碼來防止用戶僅在文本開頭添加空格。 如果有人復制並粘貼在輸入中第一個空格處帶有空格的文本,以刪除這些空格,該怎么辦?
這是我的代碼:
$('.locField').on('keydown', function(e) { if (e.which === 32 && e.target.selectionStart === 0) { return false; } });
.myform { background:#eee; padding:15px; width:100%; } .locField { width:80%; padding:12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="myform"><input placeholder="Try to add a space at the beggining..." type="text" class="locField"/> </div>
PS:為了使我的問題更清楚,請不要建議我使用“ .trim”功能,因為我只想在文本開頭刪除空格。
基於@IRR的建議,這是對我有用的代碼:
$('.locField').on('keydown', function(e) { if (e.which === 32 && e.target.selectionStart === 0) { return false; } }); $('.locField').on("input", function () { $(this).val($(this).val().replace(/^\\s+/g, '')); });
.myform { background:#eee; padding:15px; width:100%; } .locField { width:80%; padding:12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="myform"><input placeholder="Try to add a space at the beggining..." type="text" class="locField"/> </div>
監聽input
事件,然后使用正則表達式替換以開始處的空格。
const input = document.getElementById('test');
input.addEventListener('input', (event) => {
input.value = input.value.replace(/^\s*(.*)$/, (wholeString, captureGroup) => captureGroup);
});
$("input[type='text'],textarea").on("paste", function (e) {
var $self = $(this);
setTimeout(function () {
$self.val(($self.val().trim()));
}, 200)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.