Insert newline <br> at the end of textarea line - javascript

I have a form (an within the form inter alia a textarea) which is send by an ajax post request to a php file. In the php file I send a html mail with the content of the form. The textarea has a fixed size (cols, rows and maxlength).
This is the textarea:
<textarea class="form-control font-consolas" id="hellotext"
wrap="hard" cols="36" rows="10" style="width: auto" maxlength="360"
data-limit-rows="true"
name="hellotext" required></textarea>
I successfully convert the new line:
var hellotext = encodeURIComponent($("#hellotext").val());
hellotext = hellotext.replace(/%0A/g,"<br>");
This is an example of a converted text:
Hello, this is a short test. Now a NewLine is coming in the word previous NewLine.
Thaaaaaaaaaaaaaaaaats a short teeeeeeeeeeeeeeeest (new line in teeeeeeest).
NeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeLine
But the text should make each line a NewLine at character 36. Of course, a whole word must not be truncated, but a word longer than 36 characters should be. As the user sees it in the input:

Why not use editable div? It automatically breaks the lines you want. Given that you provide the right styling to the receiving end. e.g. white-space: pre-line
Click here to know how to add the div manually to the form: Getting value from contenteditable div
let editablediv = document.querySelector('div')
function output(str){
document.querySelector('pre').textContent=str
}
editablediv.addEventListener('keyup',function(event){
output(event.target.innerText)
} )
let msg = 'Nehemiah 8:10 \n\n Do not grieve, for the joy of the Lord is your strength. Isaiah 41:10 So do not fear, for I am with you; do not be dismayed, for I am your God. I will strengthen you and help you; I will uphold you with my righteous right hand.'
editablediv.textContent=msg
output(msg)
pre{
white-space:pre-line;
width:50%;
}
#ed{
border:1px solid #000;
width:50%;
}
<label for=ed><h3>Editable Div</h3>
Click on the box below to edit it;</label>
<div id=ed contenteditable=true></div>
<h3>Output</h3>
<pre></pre>

Related

Limit line breaks in textarea

I have a text area, where i want to allow users to make line break by pressing enter, but i want to limit that to only one break, because then the users could add as many breaks they want, creating huge white space in the output.
<textarea maxLength={3000} onChange={(e) => setPersonBio(e.target.value)} value={personBio} type="text" rows="5" className="bio-content" placeholder="Enter something about yourself..."></textarea>
And then i display it in <p> tag with white-space: pre-line;
My question is how to limit the amount of breaks user can enter, or delete the additional ones after submitting.
You can use the String methods search and include inside a while loop to remove all but one of a given repeated character.
text = "abc\n\n\ndef\n\nghi";
document.write('<textarea rows=6>'+text+'</textarea>');
while (text.includes("\n\n"))
text = text.replace("\n\n","\n");
document.write('<textarea rows=6>'+text+'</textarea>');
You could try this:
<textarea maxLength={3000} onChange=textAreaChange(e) value={personBio} type="text" rows="5" className="bio-content" placeholder="Enter something about yourself..."></textarea>
var pre="";
function textAreaChange(e){
if(e.target.value.split("\n").length>1){
e.target.value=pre;
return;
};
setPersonBio(e.target.value);
pre=e.target.value;
};
Add the javascript to where you keep all your other javascript for this site.

add new line in textarea not working in my CI project [duplicate]

How do I save user-entered line breaks from a <textarea> HTML element to a database?
It always removes the line breaks.
TextArea HTML element is preserving the white space in the database.
The problem appears when trying to display the \n on the web browser, which will fail.
To display \n in the web browser use :
<p style="white-space: pre-line">multi-line text</p>
When displaying the content you need to convert line breaks into <br /> tags, otherwise the web browser won't display them. This is probably why you think they aren't being saved. If you're using PHP, use the nl2br() function to do this. In other languages you could do a string replace, replacing all occurrences of "\n" with "<br />".
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
I just learnt to use php's nl2br function and it is working fine for me.
I'm using it to style how my users receive an email when sent from another user.
Your problem will be solved using 'white-space' property: simply use:
<textarea name="description" id="description" style="white-space: pre-wrap;"></textarea>
And continue your work.
I know from experience that Browser text areas are less well-behaved than one would like, especially with regard to line breaks.
You could can to see if javascript would be able to interrogate the text area and find the line breaks before the text is sent to the server and so send the data in a more well-formatted way. But the amount of javascript debugging necessary to make this work across multiple browsers is probably not worth the effort.
Perhaps you should say that format you are trying to capture your data. There may be a better way to get the data than keeping track of line-breaks - though lines breaks can seem like any easy thing to capture in user input.
I noticed that breakable content saved normally if textarea is inside a html form. But if I use textarea without any form and try to edit a long text in it, insert line breaks and save content via ajax, it's saved as a merged text into database
Use PHP nl2br() Function while saving data from textarea to database
like below
<textarea
name="PostContent"
class="form-control"
rows="12" cols="30"
id="PostContent"
required=""
style="white-space: pre-wrap; text-indent: 50px;"
>
</textarea>
$PostContent=$_POST["PostContent"];
$output =nl2br($PostContent);
use $output variable to save to Database
you can add text in the text area and see the formatted text below.
function ex() {
const text = document.getElementById("description").value;
const ss = document.getElementById("add");
ss.textContent = text;
}
<textarea name="description" id="description" style="white-space: pre-wrap;"></textarea>
</br>
<button onclick="ex();">check</button>
</br>
<p style="white-space: pre-line" id="add"></p>
<style>
p {
color: red;
text-align: center;
}
</style>

Python selenium set value of textarea with javascript doen'ts work

I use chrome driver to send text by send_key method in the beginning. But according to this question,chrome driver does not seem to support sending emoji. So I use a script injection to send emoji according to the link.
Here is the code, I use send_key and javascript to send text for testing:
reply_area = WebDriverWait(self.webdriver,1).until(expected_conditions.element_to_be_clickable(locator_))
reply_area.send_keys("Send_key")
JS_ADD_TEXT_TO_INPUT ="""
var element = arguments[0], txt = arguments[1];
element.value += txt;
element.dispatchEvent(new Event('change'));
"""
txt = "😊😊👍👍👍\n" \
"😊👍👍👍😊👍👍👍😊👍👍👍😂😂\n" \
"😊👍👍👍😊😊"
self.webdriver.execute_script(JS_ADD_TEXT_TO_INPUT, reply_area, txt)
It seems work by this image. But the number of text is wrong.
And after I click the text area on the website, only the text sent by send_key() is left.
I know I can use GeckoDriver to send emoji by send_key() according to this, but I want to understand thoroughly, and it seems work by the comment left below the question.
The website I tested can only be seen when you are a seller, so I can't provide the url for testing.
Thank you All.
[Updated]
Here is the html.
<div data-v-4e626831="" class="reply-comment">
<div data-v-4e626831="" class="shopee-input shopee-input__area">
<textarea type="textarea" placeholder="Please enter your reply" resize="none" rows="2" minrows="2" maxlength="500" restrictiontype="input" class="shopee-input__inner shopee-input__inner--normal" style="resize: none; min-height: 71px;"></textarea>
</div>
<div data-v-4e626831="" class="des">30/500</div> <!-- This is the number of word -->
</div>

Include space from input

My user wants an input field where he can enter a message, which I will then have displayed as a scrolling marquee across the page. He wants to be able to include empty spaces, for example,
"Employees please look up."
My textarea, when I get the text, doesn't notice the space. Any way to get that?
I know this is an odd request - google only tells me how to remove whitespace, not include it.
var text = $('textarea').val();
<textarea class='messageInput'></textarea>
I am pretty sure that you are getting the value with all the white-spaces right, the problem is in the displaying of the value in your (probably) custom div. The best way would be to set white-space: pre on that element which (as the option suggests) will preserve white-space. ;) Example:
<div id="foo" style="white-space: pre"><!-- insert text here --></div>
And ignore all the &nbps; suggestions which are essentially modifying the text content. CSS is the right way to do this!
You need to convert space characters into non-breaking spaces, which can be done using String.prototype.replace() with a regular expression:
$('#text').html($('textarea').val().replace(/ /g, '&nbsp'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='messageInput'>employees hello</textarea>
<p id="text"></p>
You need / /g so that it will match all spaces, not just the first one, which .replace(' '...) would do.
Note that smajl's suggestion is less invasive and probably better, but I'll leave this for posterity.
The spaces in the value are not ignored. It's that the browser by default "compresses" duplicate spaces. Use white-space:pre;
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
document.getElementById("button").onclick = function() {
var content = document.getElementById("input").value;
console.log(content);
document.getElementById("result").innerHTML = content;
}
#result {
white-space:pre;
}
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
EDIT: too late ;)

How does the Google Keep text input work?

I'm looking into creating a text editor for my site and really liked how Google Keep does their text input. At first look based on the HTML, they don't appear use input fields / text areas but rather some sort of javascript mode of input that takes text input and generates the HTML equivalent that text and places it in the DOM. So is it likely that they built their own input functionality to allow them and the user to manipulate the content they put in? Or is it more likely that they have an all purpose input field or something that captures the data and it's just hidden from view?
This is all I see when I go looking into the DevTools
<div contenteditable="true" aria-multiline="true" role="textbox" class="notranslate IZ65Hb-YPqjbf h1U9Be-YPqjbf" tabindex="0" spellcheck="true" dir="ltr">
This is their "input field"
<br>
That renders html
<br>
Based on the text that's entered
<br>
But I want to know how I should be capturing this text
</div>
The contenteditable="true" and role="textbox" tell the DOM to treat the <div> element like a <textbox>. According to the WAI-ARIA Standards, this approach allows those with reading impairments to navigate the screen more easily, as a screen reader would have a better idea of what elements are on the page.
Without seeing the rendered DOM, I can't be 100% sure what Google is doing, but it is very easy to manipulate the DOM based on user input as such. In the following example, I'm using targeting the input element, and then creating an onkeyup function that writes the content in a secondary 'output' <div>. This second <div> mirrors the input in the example, though can be coded to send the input to another page (or database) with AJAX, included elsewhere on the page, or styled to format the input in a nicer fashion.
// Initial text
document.getElementById('output').innerHTML = document.getElementsByClassName('h1U9Be-YPqjbf')[0].innerHTML
// On change
document.getElementsByClassName('h1U9Be-YPqjbf')[0].onkeyup = function() {
document.getElementById('output').innerHTML = document.getElementsByClassName('h1U9Be-YPqjbf')[0].innerHTML
}
.h1U9Be-YPqjbf {
border: 1px solid blue;
}
#output {
margin-top: 20px;
border: 1px solid red;
}
<div contenteditable="true" aria-multiline="true" role="textbox" class="notranslate IZ65Hb-YPqjbf h1U9Be-YPqjbf" tabindex="0" spellcheck="true" dir="ltr">
This is their "input field"
<br> That renders html
<br> Based on the text that's entered
<br> But I want to know how I should be capturing this text
</div>
<div id="output"></div>
Hope this helps! :)
I thinks behind the scenes they uses Firebase three way binding.
You can achieve the result with Angular and Firebase. Both are free to get started.
More here link

Categories

Resources