I have a text-area with no text inside, if i hit enter the cursor move's to the second row and blinking. I put some code inside to stop it but still nothing the text-area moves down. example:
function areaOnkeydown(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 13) {
if (_text.value === '') {
return; // if there's no text and hit enter.. // return but move to second row
} else {
// do something here..
}
}
}
With 2 words on enter if text-area doesn't have any text remain as is do nothing.
Thanks in advance.
CodePudding user response:
Just cancel the event when the value is empty. This is done using Event.preventDefault()
function.
function areaOnkeydown(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var value = e.target.value
if (code === 13) {
if (value === '') {
e.preventDefault()
return;
}
}
}
textarea.addEventListener("keydown", areaOnkeydown)
<textarea id="textarea" rows="4"></textarea>
CodePudding user response:
Solved. I post the here the solution that works for me. No more new empty line on enter after text in text-area.
function areaOnkeydown(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var value = e.target.value;
if (code === 13) {
if (value === '') {
if (value && value.indexOf('\n') > -1) {
e.preventDefault();
return;
}
e.preventDefault();
return;
}
onSendText(e); // also i put the e.preventDefault(); here
}
}
Thanks all for the help!