White space textarea in html - javascript

I have a website that has a form. In the form I have a textarea field. When this is filled and displayed in the manner below
eg . this is how it was written in the textarea box
The manager,
Abc limited,
private bag,
earth.
It displayed like this
The manager, Abc limited, private bag, earth.
how can I make it stay the way it was written

The only way I was able to recreate your error was by misspelling <textarea> as <text area>. When the space is added, the error occurs. When properly spelled line breaks are preserved.

You can use the innerText attribute of the element that will hold the textarea value.
Important: At the backend side, you have to preserve the \n in the Database or whatever it's being used to store the data to get it back and render the content exactly as was saved.
var div = document.querySelector('div');
var textarea = document.querySelector('textarea');
div.innerText = textarea.value;
textarea.addEventListener('input', function() {
div.innerText = this.value;
});
<h3>Enter text and press enter</h3>
<small>The entered text will appear automatically</small>
<p>
<textarea>
The manager,
Abc limited,
private bag,
earth.</textarea>
<div></div>

You will have to use \n for line breaks inside textarea

If you are using php, then you can echo echo nl2br($textarea);
https://www.w3schools.com/php/func_string_nl2br.asp
or for jquery
jQuery convert line breaks to br (nl2br equivalent)

Well you are not really giving us a lot to go on how you print the text field. But my guess is that if you use php you should wrap your variable in a nl2br() function.
Get more information here:
http://php.net/manual/en/function.nl2br.php

HTML ignores new lines/whitespace unless you style the element with white-space:pre like in this example

Related

How can I replace the value of a textarea in Chrome as user?

I'm using Google Chrome.
Is there a simple way to create something like a user script (with javascript?) that automatically replaces the content of a certain textarea (id: svn) with another one, preferable by using a regex replace function?
For example, if the textarea by default contains Text "any text"-Set Text, then I want to replace it with Text Set any text Set. (Basically replace ".*"-Set with Set .*)
You can make a bookmark tool.
1 . Open a new tab, save it.
2 . Choose to edit the new bookmark.
3 . Paste js code in the url.
The code may look like this:
javascript:
var el = document.getElementById('svn');
el.value = el.value.replace(/pattern/,'text'); /* edit your pattern here */
el.disable = true; /* keep textarea editable */
When bookmark clicked,the code will be excuted. All spaces are better replaced with %20. Keep all codes in a single line, that is:
javascript:var%20el=document.getElementById('svn');el.value=el.value.replace(/pattern/,'text');el.disable=true;
Good luck.

String with new line and tabs to display in HTML

I have a string coming from my java backend which is formatted to display in a certain way, the new line, tab and space characters are in certain positions.
How do I get this to display the same way in HTML?
For example, say I have the current string in Javascript as so:
var str = "\t\tTitle \n Some text \t\t\t more text";
Browsers typically strip out extra white space, you might need to put it inside a preformatted text block or use white-space: pre
var pre = document.createElement("pre");
pre.innerHTML = str;
document.appendChild(pre);
Also yes, you need to use backslahes too, as mentioned about.
I might be late but just in order to help if a beginner like me is facing this kind of problem.
You can add a css class to the html tag where you want to display the data. In my case I am using ngFor of Angular 2. The data coming from my back end had line breaks and tabs. So I just added a class to the html tag with a css white-spacing style as follows.
Backend Data"title": "postIssueResponse() {\n\tthis.parent.postIssueResponse(this.issueId, this.newResponse);\n console.log(this.newResponse);\n this.newResponse \u003d \"\";\n}"
<p class="response-title">{{myData?.title}}</p>
And the css
.response-title {
white-space:pre;
}
This one do the job perfectly.
You can use textarea also. here is a Working Fiddle
MDN textarea

Javascript to fill a formatted text field on a web site

I know virtually nothing about Javascript. By a monkey-see, monkey-do approach I’ve managed to successfully use Javascript within AppleScript/Safari to fill text fields on a web-site using the following command:
do JavaScript "document.getElementById('ElementID').value ='TextToEnter';" in document 1
I’ve been able to enter text into all fields except one. The fields that work are labeled as input type="text”. The field that doesn’t work is complex in that the entered text can be formatted (bold, italics, underline, alignment, etc.) after entry. Assuming I’ve identified the correct source code for this element it looks as follows PRIOR TO any text entry:
<body id="tinymce" class="mce-content-body " onload="window.parent.tinymce.get('fax_text').fire('load');" contenteditable="true" spellcheck="false"><p><br data-mce-bogus="1"></p></body>
Depending on how its viewed, sometimes the p and br tags appear on separate lines but everything is otherwise identical.
After manual entry of text (“INSERT TEXT HERE”) directly into the web page's text field the source code becomes:
<body id="tinymce" class="mce-content-body " onload="window.parent.tinymce.get('fax_text').fire('load');" contenteditable="true" spellcheck="false"><p>INSERT TEXT HERE</p></body>
The following did not work (wrapped in Applescript):
document.getElementById('tinymce').value ='INSERT TEXT HERE';
It produces the error: "missing value".
As per #WhiteHat, the following with n= 0-4 inserted text at several spots on the page but not in the targeted text field; n > 4 resulted in the "missing value" error:
document.getElementsByTagName('p')[n].innerHTML ='Insert text here';
I tried targeting the br tag but to no avail. How do I target this text field with Javascript? Note: I do not need to format the entered text.
You need to access the <p> element, which is just after the body of the document, as such...
document.getElementsByTagName('P')[0].innerHTML = 'your text'
The getElementsByTagName function returns an array of all elements with the tag name you provide, P in this case. You're looking for the first one, hence the [0].
The innerHTML property will allow you to set the contents of the <p> element.
Following is a good JavaScript reference...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
The following reference is for the web page, or Document Object Model (DOM).
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
And tinymce is a 3rd party JavaScript library which allows the rich edit functionality.
http://www.tinymce.com/
Based on the comments, the specific field you are looking for is named fax_text. Here is the source, it's in a textarea tag, take note on which function to use TagName vs. Name...
document.getElementsByName('fax_text')[0].value = 'This is my text!';
document.getElementsByTagName('textarea')[0].value =
document.getElementsByName('fax_text')[0].value +
'\nThis is additional text...';
<textarea rows="5" name="fax_text" cols="36" class="mytext"></textarea>
This text field is in an iFrame.
This iFrame contains an HTML document (<html><head><body>).
To get this document, you need the_iFrame.contentDocument.
do JavaScript "var ifr = document.getElementById('fax_text_ifr'); ifr.contentDocument.getElementsByTagName('p')[0].innerHTML = 'some text';" in document 1

jQuery empty textarea that contains data

Curious problem. I need to empty a <textarea> then replace it with other content. The tests in the JSFiddle will work if nothing is manually typed, but as soon as anything is entered in the textarea by hand, the methods will cease to work.
http://jsfiddle.net/ecFjH/
I understand that I can simply just .val('New stuff here'), however I need HTML entities such as > and < to appear as < and >, which .val() will not accomplish.
It sounds like your real problem is that you want to decode HTML entities to render them in a text area. You could use the following to do this:
var content = 'text > HTML';
$('#myText').val($('<div/>').html(content).text());
However, you should only do this with trusted content. If the content for the textarea is not created by you, it could contain malicious HTML, which you would unsafely be creating on the page.
For a more thorough example, see this answer to essentially the same question; note that the accepted answer repeats the above, but the linked answer is safer.
Your text area has no html. use just $('#myText').val('Button 2 was pressed'); that will remove the previous content and put the text "Button 2 was pressed".
Check here (updated with < and >)

Make my textbox understand html img tag

When inserting a new emoji inside my textbox i want to be displayed as the emoji image and not the emoji symbol how can i do that like instead of ( ':)'--> put the image represent it inside my textbox )
One way: Instead of a text box, use a <div contenteditable="true"></div>. As the user types, change occurrences of the smiley for the image. When the form is submitted, your javascript needs to translate the contents of that div back into plain text and put it into a field for submission.
If you want to use images, then it would require you to change your HTML significantly. You would need to make use of the Content Editable functionality on something like a <span>, rather than a regular input box. You'd then need JavaScript code to monitor keypress events and whenever it sees a :) (or whatever), it replaces the code with the appropriate <img>.
A quick-and-dirty solution that sticks with your text box, however, would be to use the same approach, but use the Unicode emoji characters (rather than images). This will only work on platforms with the appropriate font glyphs -- although the common smilies are more widely supported -- but it gives you the idea:
HTML:
<input class="emojify" type="text" />
JavaScript (using jQuery, to make everyone's life easier):
$(document).ready(function() {
// Map plaintext smilies to Unicode equivalents
var emoji = {
':)': '\u263a',
':(': '\u2639'
},
// Function to escape regular expressions
reEscape = function(s) {
return s.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
$('input.emojify').keyup(function() {
var text = $(this).val();
// See if any of our emoji exist in the text and replace with Unicode
$.each(emoji, function(plaintext, unicode) {
text = text.replace(new RegExp(reEscape(plaintext), 'g'), unicode);
});
// Replace text with new values
$(this).val(text);
});
});
Here's a working demo on jsFiddle. Note that the caret position will be reset every time the keyup event is triggered. I'm sure you can work around that somehow, but this code suffices to illustrate the process.

Categories