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));
});
If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!
To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.
<textarea> does not support the value attribute.
Insert SQL carriage return and line feed in a string In SQL Server, we can use the CHAR function with ASCII number code. We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With