Note: The code passed the test in the actual project. I have omitted some unimportant parts. You can focus on the color-marked parts.
Foreplay:
Question: Why do you do this? ?
Answer: There is a function in the project to save the entered text field text into the database. 'When viewing' obtains the corresponding data from the database and displays it in the text field. During the development, I found that the newline character is obtained using jquery's val() or text() without processing it. There is no newline character in the saved database. Naturally, there is no newline character when it is taken out and displayed! As a result, I wrote the following article... It's a bit verbose!
Copy the code code as follows:
<%@ page contentType="text/html;charset=UTF-8" %>
<script type="text/javascript">
// Text field line wrapping processing
// During initialization, process the data returned from the background and replace @@@@ with newline characters /n/r
$(document).ready(function(){
var content = 'Value obtained from the background';
if(content !='' ){
//Global replacement
content = content.replace(/@@@@/g,'/n/r');
$("#content").attr("value",content);
}
});
// Replace the newline character /n/r with @@@@ when submitting and saving.
function doSubmit() {
var content = $("#content").val().replace(//n/g,"@@@@");
if(content == null || content==""){
alert("Please fill in the remarks!");
return;
}
$("#updateForm").attr("method","get");
$("#updateForm").attr("action", url);
$("#updateForm").submit();
}
</script>
<div>
<div>
<div>
<div><p><font face="Chinese regular script" size="10">Interview plan</font></p>
</div>
<div>
<div> Plan<br><hr></div>
<div>
Remarks:
<div>
<textarea id="content" rows="15" cols="50"></textarea>
</div>
</div>
</div>
<div>
<a id="submit_btn" onclick="doSubmit();">Save</a>
</div>
<form id="updateForm" method="get">
</form>
</div>
</div>
</div>