简体   繁体   中英

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?

I have an input field and i am using the following code to prevent users of adding white spaces only at the beginning of the text. How can i make it also so if someone copy and paste text that has white spaces at the first place of the text in the input to remove those spaces?

Here's my code:

 $('.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: To make my question more clear, please do not suggest me to use the ".trim" function as i want to remove the white spaces ONLY at the beginning of the text.

ok based on the suggestion of @IRR this is the code that worked for me:

  $('.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> 

Listen to the input event, and then trim the spaces at the beginning with a replace using regex.

const input = document.getElementById('test');

input.addEventListener('input', (event) => {
    input.value = input.value.replace(/^\s*(.*)$/, (wholeString, captureGroup) => captureGroup);
});

Here's a fiddle that demonstrates it

$("input[type='text'],textarea").on("paste", function (e) {
    var $self = $(this);
    setTimeout(function () {
        $self.val(($self.val().trim()));
    }, 200)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM