How to prevent with trim jquery at textarea while write to check

Here is the fiddle. And also possible to prevent enter it?


first, trim() is a function, so don’t forget to stick parentheses on the end. Second, while you will be trimming the value of the textArea fine, you don’t assign it back INTO the textArea: $(this).val($(this).val().trim() );

Amazing thank you. By the way you have idea how to prevent space more than once?

So it’s largely a matter of what events you’ll listen for – the keydown event is the place to capture the enter key, but a lousy place to prevent the space bar from being hit. If you .trim() spaces there, then the user won’t be able to put spaces between words. :wink:

The better place to handle .trim()ming your spaces? When the textarea loses focus, whether the user moves to another form field, or clicks on a submit button. When the textarea is exited, then calling .trim() can remove trailing and leading spaces without impacting the spaces between words.

And when you add event listeners like this, then any time the keydown event fires, the event handler runs. Any time the blur event fires (when the field loses focus), the event handler for THAT runs.

Here’s the code I tested with, and it works. If the above hints don’t get you to quite where you think you want to be, I’m “spoilering” my code, and I’ve commented it pretty extensively to explain each step of the way.

// Start by saving a reference to the textarea
let myTextEl = $("#textarea");

 * If we wish to capture the return key being pressed, then
 *  we likely want to use the keydown event to capture that,
 *  and the space thing we want to do when the text area
 *  loses focus. If we were to trim spaces on the keydown as
 *  well, then the user would never be able to add spaces
 *  between words!
myTextEl.on("keydown", (evt)=>{
  // We get an Event object from each system event, which I'm 
  //   assigning to the parameter 'evt'. In the case of keydown,
  //   evt.which tells us the ASCII code of the key pressed. We
  //   want to stop the enter key, which is ASCII 13.
  if(evt.which === 13){
    // By preventing the default behavior, the keystroke is
    //   filtered from going into the textarea.
}).on("blur", (evt) =>{
  // When the textarea loses focus, we want to trim away any
  //   leading or trailing spaces/tabs/newlines. trim() will 
  //   handle all that for us.
  // We use .val() for both getting and setting the value.
  myTextEl.val(myTextEl.val().trim() );
1 Like