PHP - Display all characters in html textarea (newline, whitespace included) - html

I have a text field in MySQL that contains an e-mail template.
I build an admin interface where the admin will be able to display the content in a <textarea></textarea> and edit it.
It works great, but I'd like to actualy see the whitespaces and the \r\n, something like Notepad++ "Show All Characters" button.
Here is the email template, as it is currently shown in textarea:
And this is how I'd like to see it, like Notepad++ shows it, displaying the newlines and the whitespaces:
How can I do that using php? Should I just escape the \r\n from the database to make them to show up, or is there an other way?
Update.
I did manage to create a toggle button that displays whitespaces and newlines, even while typing.
See example demo http://jsfiddle.net/QshDd/80/
Here is where I found some of this interesting code: http://www.kristofdegrave.be/2012/03/javascript-change-entered-character-in.html

An approach:
before adding the text to the textarea you could make an replacement of the newline characters with some other "special" characters. Then at post before saving the content of textarea in mysql switch the "special" characters with the newline characters

You can use TinyMCE. Here is the reference link http://www.tinymce.com/tryit/full.php
Just give id to your text area like
<textarea id="tinyeditor" ></textarea>
In your script customize your requirement like
var editor = new TINY.editor.edit('editor', {
id: 'tinyeditor',
width: 584,
height: 175,
cssclass: 'tinyeditor',
controlclass: 'tinyeditor-control',
rowclass: 'tinyeditor-header',
dividerclass: 'tinyeditor-divider',
controls: ['bold', 'italic', 'underline', 'strikethrough', '|', 'subscript', 'superscript', '|',
'orderedlist', 'unorderedlist', '|', 'outdent', 'indent', '|', 'leftalign',
'centeralign', 'rightalign', 'blockjustify', '|', 'unformat', '|', 'undo', 'redo', 'n',
'font', 'size', 'style', '|', 'image', 'hr', 'link', 'unlink', '|', 'print'],
footer: true,
fonts: ['Verdana','Arial','Georgia','Trebuchet MS'],
xhtml: true,
cssfile: 'custom.css',
bodyid: 'editor',
footerclass: 'tinyeditor-footer',
toggle: {text: 'source', activetext: 'wysiwyg', cssclass: 'toggle'},
resize: {cssclass: 'resize'}
});
And last get value from data base in textarea on document ready
$(document).ready(function(){
var template_data = '<?php echo $database_result; ?>';
$("iframe").contents().find("#editor").html(template_data);
});

Related

Ruby on Rails content_tag is deprecated, but I can't replicate its nesting capabilities using tag

The project I'm working on requires some of the data table's column titles to be referenced/defined in a footnote below the table.
As it's dynamic content that will be looped over depending on how many of the column titles require footnotes, I need to handle most of this in via models/helpers. I have been able to replicate the html our US designer wants using content_tag, but rubocop is whining about the use of content tag and says I should be using tag instead. But I can't get the nesting of the html tags to work at all using the tag method.
The section html I'm trying to produce is this (which will be repeated for as many footnotes are needed):
<li id="id" class="p-2">
<dl class="m-0"><dt class="d-inline">Unusual term: </dt>
<dd class="d-inline">Text with the definition of the term.↵</dd>
</dl>
</li>
And the content_tag based code that works to produce it is this:
content_tag(:li,
content_tag(:dl, [
content_tag(:dt, 'Unusual term: ', class: "d-inline"),
content_tag(:dd, [
'Text with the definition of the term.',
content_tag(:a, '↵', href: '#id-ref', aria: { label: "Back to content" })
].join.html_safe, class: "d-inline")
].join.html_safe, class: "m-0"),
id: 'id',
class: "p-2")
When I switch to using tag, the problem I'm coming up against is getting both the <dt> and <dd> tags, which both have content, to nest inside the <dl> tag (and also the <a> tag, which also has content, to nest within the aforementioned <dd> tag). The tag method only seems to output the last piece of nested content and ignores any other content that precedes it.
This is the nesting of the tag method that I've tried:
tag.li id: 'id', class: 'p-2' do
tag.dl class: 'm-0' do
(tag.dt 'Unusual term: ', class: 'd-inline') +
(tag.dd 'Text with the definition of the term.', class: 'd-inline' do
(tag.a arrow, href: anchor, aria: { label: 'Back to content' })
end)
end
end
And this is the output it's giving me.
<li id="id" class="p-2">
<dl class="m-0"><dt class="d-inline">Unusual term: </dt>
<dd class="d-inline">↵</dd>
</dl>
</li>
As you can see, it's close, but it's missing the text content of the <dd> tag, which should be output just before the <a> tag starts.
Can anyone help? Is there a way to nest tags without losing content? Or should I just give up and write a partial with the actual html code written out...?
It looks to me like content_tag and tag are part of rails 6.1.3.1. It looks like only what is being deprecated is the format of the tag helper defaulting to an XHMTL empty tag instead of an HTML 5 type of tag. There are reports of incorrect behavior by rubocop targeting content_tag when it is tag which should be targeted.
You might check on the arguments to content_tag for empty tags since it might not be defaulting the same way as before.
tag.li(id: 'id', class: 'p-2') do
tag.dl(class: 'm-0') do
concat tag.dt('Unusual term: ', class: 'd-inline')
concat tag.dd(class: 'd-inline') do
concat 'Text with the definition of the term. '
concat tag.a(arrow, href: anchor, aria: { label: 'Back to content' })
end
end
end
Each content_tag or tag has its own string buffer - by using concat you output to that string buffer. That lets you output multiple times in the block without dealing with string concatenation and #html_safe. This string buffer is the return value of content_tag/tag.
This really works no matter if you are using content_tag or tag.
See:
https://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat
Using concat and capture to clean up custom Rails helpers
I have now worked out a way to nest these tag methods to achieve the desired html output, using the following code:
link = link_to ' ↵', '#id-ref', aria: { label: 'Back to content' }
tag.li(id: 'id', class: 'p-2') do
tag.dl(class: 'm-0') do
(tag.dt 'Unusual term: ', class: 'd-inline') +
(tag.dd ('Text with the definition of the term.' + link).html_safe, class: 'd-inline')
end
end
If anyone has an alternative solution, I'd love to hear it, but I think this will serve for now.
EDIT TO ADD NEW SOLUTION
Thanks to #max suggestion of using concat to rid me of #html_safe I now have a block of code that I, my ux designer and rubocop will all be happy with! Here it is:
tag.li(id: 'id', class: 'p-2') do
tag.dl(class: 'm-0') do
tag.dt('Unusual term:', class: 'd-inline') + ' ' +
tag.dd(class: 'd-inline') do
concat 'Text with the definition of the term.'
concat tag.a(' ↵', href: '#id-ref', aria: { label: 'Back to content' })
end
end
end
Thanks again for everyone's input on my question. I really appreciate it.

HTML is shown as plain text in dojo widget

I have a dojo widget with generated content, text message in my case.
Message text is a formatted text with <b>, <i> etc. tags. When I put it to my widget via ${messageText} it is shown as it is a plain text.
How to make my widget parse all these tags to DOM nodes?
upd
.jsp fragment:
<script>
(new MyWidget({
text: "<b>message</b>"
}).placeAt(dojo.byId("placeWidgetHere");
</script>
<div id="placeWidgetHere"></div>
widget .html template:
<div>${text}</div>
Instead of using substitution variables (which is not recommended), you can use an attribute map on your custom widget.
<div>
<span data-dojo-attach-point="messageTextNode"></span>
</div>
declare('MyWidget'], [TemplatedMixin], {
template: ...,
messageText: '',
_setMessageTextAttr: { node: "messageTextNode", type: "innerHTML" },
});
new MyWidget({
messageText: "<b>message</b>"
}, "placeWidgetHere");
The problem is that messageText has "<" and ">" symbols converted to "<" and ">" respectively.
I added .replace(/</g, "<").replace(/>/g, ">") to messageText and that began to work properly.
Thanks to everyone who tried to help me.

HTML : How to retain formatting in textarea?

I am using HTML textarea for user to input some data and save that to App Engine's model
The problem is that when I retrieve the content it is just text and all formatting is gone
The reason is because in textarea there is no formatting that we can make
Question:
is there any way to retain the format that user provides?
is there any other element(other than textarea), that i'll have to use?(which one?)
P.S I am very new to area of web development and working on my first project
Thank you
What you want is a Rich Text Editor. The standard HTML <textarea> tag only accepts plain text (even if the text is or includes HTML markup). There are a lot of example out there (including some listed on the page linked) but I would highly recommend using a prepackaged one for this. Coding your own is fairly complicated for people who are new, and even for a lot who have some experience. Both TinyMCE and CKEditor are very common ones, but there are many others as well.
A text box is like wordpad, you cant format it, if you paste in from word or any other formatted text it will wipe all the formatting and you will be left with just the text.
You need add an editor to the text areas, I use TinyMCE, but there are many other out there too.
To implement you need to have all the source (which you can get from TinyMCE) in your web directory.
Here's an example which you can try:
Add this the the head section of your page:
<script language="javascript" type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode: "exact",
elements : "elm1",
theme_advanced_toolbar_location : "top",
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
+ "justifyleft,justifycenter,justifyright,justifyfull,formatselect,"
+ "bullist,numlist,outdent,indent",
theme_advanced_buttons2 : "link,unlink,anchor,image,separator,"
+"undo,redo,cleanup,code,separator,sub,sup,charmap",
theme_advanced_buttons3 : "",
height:"350px",
width:"600px"
});
</script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Skin options
skin : "o2k7",
skin_variant : "silver",
// Example content CSS (should be your site CSS)
content_css : "css/example.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
</script>
Then to call the textarea:
<textarea name="content" style="width:100%">YOUR TEXT HERE</textarea>
NB: You need to download and have in your directory the js files for <script language="javascript" type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
Hope this helps!
This won't solve the case when you want somebody to be able to format their text (e.g. with WYSIWYG bold buttons etc.), but if you want to be able to accept pre-formatted HTML (e.g. copy and paste from other HTML source such as a webpage), then you can do this:
<form ...>
<label>Paste your HTML in the box below</label>
<textarea style='display:none' id='foo'></textarea>
<div id='htmlsource' contenteditable style='border:solid 1px black;padding:1em;width:100%;min-height:2em;' ></div>
<input type='submit' />
</form>
<script>
jQuery(function(){
jQuery('form').submit( function(e) {
jQuery('textarea').val( jQuery('#htmlsource').html() );
});
});
</script>
This uses a contenteditable div element which you can format to look like an input box and will accept pasted HTML, and a hidden textarea#foo which will be populated with the pasted HTML just before the form is submitted.
Note that this is not an accessible solution as it stands.
Depending on your goal for the programm it could already be sufficient to just add "pre" tags left and right to the input of your textarea. for example if your code submits to a form whatever is inside a textarea and than echos it in the target File this would already work.
> File 1:
>
> <form action="Output.php" methode=post>
> <textarea name="Input"></textarea>
> </form>
>
> File Output.php
>
> $UserInput = $_POST["Input"];
> $UserInput = "<pre>" . $UserInput . "</pre>"
> echo $UserInput
this already will retain all Enters for example that where used in the original user input and echo them correctly
If you retrieve the content from the App Engine Saving the Content with the pre tags added already in most cases does the trick

Javascript Textarea Issue

I'm importing data from youtube into a textarea using Javascript.
If you I simply place my Javascript code onto a blank area it displays the information fine, but for some reason it doesn't allow me to paste a same code into a textarea.
Here is my code:
<textarea rows="10" id="bandsvideodescription" name="bandsvideodescription">
<script type="text/javascript">
function youtubeFeedCallback( data )
{
document.writeln( '' + data.entry[ "media$group" ][ "media$description" ].$t.replace( /\n/g, '' ) + '' );
}
</script>
</textarea>
Any help would be great,
Thanks.
Textareas are defined as:
<!ELEMENT TEXTAREA - - (#PCDATA) -- multi-line text field -->
They can only contain PCDATA, which means no elements (including <script> elements).
Move the script to after the control, then get a reference to it (e.g. with document.getElementById) and set its value property instead of trying to write it out as the document loads.
Your script is interpreted as HTML code. You should escape angle brackets, like this:
<textarea rows="10" id="bandsvideodescription" name="bandsvideodescription">
<script type="text/javascript">
function youtubeFeedCallback( data )
{
document.writeln( '' + data.entry[ "media$group" ][ "media$description" ].$t.replace( /\n/g, '' ) + '' );
}
</script>
</textarea>
you can't put script tags <script> in a textarea you can't even put any html tag in a textarea.
It will consider it as the default value ;)
And escaping it with > our < will nt change anything because it's already escaped in the textarea to show it as simple text

CKEditor remove spaces/tabs from between headings

CKEditor does this whenever I add a heading tag:
<h2>
Mai 2010</h2>
How can I remove the new line and spaces after the h2 starting tag, please?
The way to do this without modifying CKEditor's source is to do the following:
CKEDITOR.on( 'instanceReady', function( ev )
{
ev.editor.dataProcessor.writer.setRules( 'p',
{
indent : false,
breakBeforeOpen : true,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : true
});
});
For more information see:
http://cksource.com/forums/viewtopic.php?f=6&t=14493
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Output_Formatting
This is the default CKEDITOR behavior for a lot of tag.
To avoid it, open the ckeditor.js file and search for this:
n.setRules('title',{indent:false,breakAfterOpen:false});
and add this rule:
n.setRules('h2',{indent:false,breakAfterOpen:false});
You can add this rule for each tag you want