Don't allow new lines in textarea
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} />;
}
}
you can check keyCode, if it is equal to 13 simply return false
$('#TEXTAREA').keypress(function(e){ if (e.keyCode == 13) return false })