kieran
kieran

Reputation: 2312

Don't allow new lines in textarea

Using jQuery how can I not allow new lines to be inserted (by pressing enter or copying in text) - In semi-pseudo code...

$('textarea').keydown(function(){
 $(this).remove_new_lines();
});

Thanks!

EDIT:

Would it be as crude as the following or is there a better way?

function removeNL(s){ 
  return s.replace(/[\n\r\t]/g,); 
}

$('textarea').keydown(function(){
 $(this).val(removeNL($(this).val));
});

Upvotes: 13

Views: 25759

Answers (3)

coreyward
coreyward

Reputation: 80140

There are two methods to do this: check each character as it is input and return false if you don't want it to show up, or on each change/keyup you can check the entire contents. While the former is more performant, it won't work in situations where the user pastes content in that includes unwanted characters. For that reason, I recommend the latter approach, something like this (which will disallow all vertical whitespace):

With jQuery:

$('textarea').on('keyup', function(){
  $(this).val($(this).val().replace(/[\r\n\v]+/g, ''));
});

Or using plain JavaScript (ES2015/ES6):

constrainInput = (event) => { 
  event.target.value = event.target.value.replace(/[\r\n\v]+/g, '')
}

document.querySelectorAll('textarea').forEach(el => {
  el.addEventListener('keyup', constrainInput)
})

Another approach is to wait until the focus leaves the textarea, then apply the transformation. This avoids janky behavior on operating systems using synthetic, conditionally active keyboard controls. The user will see newlines until they leave the field, though, so be aware. To do this, just change the above event listener to listen for blur rather than keyup.

If you're using React, you have it made because it avoids issues with mobile browsers while letting you manage the value as it changes using controlled components:

class TextArea extends React.PureComponent {
  state = {
    value: ""
  };

  handleChange = event => {
    const value = event.target.value.replace(/[\r\n\v]+/g, "");
    this.setState({ value });
  };

  render() {
    return <textarea onChange={this.handleChange} value={this.state.value} />;
  }
}

Upvotes: 26

David Houde
David Houde

Reputation: 4778

$('textarea').keydown(function(e){
 var s = $('textarea').val();
 while (s.indexOf("\n") > -1)
  s = s.replace("\n","");
 $('textarea').val(s);
});

Upvotes: 1

Fatih Acet
Fatih Acet

Reputation: 29569

you can check keyCode, if it is equal to 13 simply return false

$('#TEXTAREA').keypress(function(e){
   if (e.keyCode == 13) return false
})

Upvotes: 9

Related Questions