I have a custom span
label with the role of textarea
where I expect to enter multi-line text into it.
.input,
.textarea {
border: 1px solid #ccc;
font-family: inherit;
font-size: inherit;
padding: 5px 50px;
}
.textarea {
display: block;
width: 1000px;
overflow: hidden;
resize: none;
min-height: 200px;
line-height: 20px;
white-space: pre-wrap;
}
.textarea[contenteditable]:empty::before {
content: "Mail Body Template";
color: gray;
}
<p><span id="mail_body_template" oninput="generate(this.value)" role="textbox" contenteditable></span></p>
However, when I print the read value of the textarea
, it appears it doesn't create new lines on pressing Enter
but can do so only with Shift Enter
.
I tried to add a onpresskey
listener on the span
to catch the Enter
and create a new line but it never works.
$(document).ready(function() {
$('#mail_body_template').on('keypress',function(e) {
if(e.which == 13) {
$('#mail_body_template').val($('#mail_body_template').val() "\r\n");
}
});
Ultimately, I want to be able to let the span
treat Enter
as a new line same as it does with Shift Enter
.
Is there a way to do that?
CodePudding user response:
the content of a contentEditable is HTML. using .val() or .value doesn't return the content of the span.
It is not a console line. You cannot use \r or \n to force a line break.
You can however insert a <br>
tag and this should allow the line break.
in order to access the value, you should use innerHTML.
your code is missing the generate function to further get where the error might be located. (The fact that you bind a keypress / Keydown event on the span also might trigger some weird behaviour we might not be able to reproduce.
function generate(myVal){
console.log("this.value : " myVal)
console.log("jqueryVal : " $("#mail_body_template").val());
console.log("innerHtml : " document.getElementById("mail_body_template").innerHTML);
console.log("jqueryHtml : " $("#mail_body_template").html());
console.log("plainText : " $("#mail_body_template").text());
}
https://jsfiddle.net/kezqs7tv/5/
Here is a js.fiddle snippet that shows what I mean.
CodePudding user response:
I think the problem is this.value
into your generate
argument function, cause .value
is for an input not for an contenteditable.
You should use .innerText
or .innerHTML
function generate(value) {
console.log(value)
}
<p><span id="mail_body_template" oninput="generate(this.innerHTML)" role="textbox" contenteditable></span></p>