Line break inside text area html - php

I'm making a form to fill in and create a pdf through, but I'm facing a problem with text area, I want the user to input text and while writting and pressing space to go back to line like this:
i want it to automatically show in the pdf but instead i get this:
how can i fix it? the code for this is:
<div class="mb-2"><textarea name="element" placeholder="Elements à fournir" class="form-control"></textarea></div>

You need to convert the line breaks from the textarea (\r or \n) into line breaks your PDF can understand (<br /> <div> <li> etc).
a simple PHP way is
$string = nl2br($string);
// converts \n to <br />
If you need to transform those line breaks on the fly (like you're capturing the input and displaying it formatted as the user types), then do it in javascript. Here is a handy function taken from: https://stackoverflow.com/a/7467863/1772933
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Here is an example of how to use that function as the user is typing
$('#TextArea').keypress(function(evt){
$('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
$('#pdfPreviewArea').html($('#TextArea').val()); // copy to #pdfPreviewArea
});

Related

Generate tooltip through * symbol

I have the following PHP code:
function word_filter()
{
$tt_tijdelijke = '';
$tt_gestoffeerd = '';
$tt_gemeubileerd = '';
str_replace('tijdelijke', '<span class="incexc-single" tooltip="'.$tt_tijdelijke.'">tijdelijke</span>');
str_replace('gestoffeerd', '<span class="incexc-single" tooltip="'.$tt_gestoffeerd.'">gestoffeerd</span>');
str_replace('gemeubileerd', '<span class="incexc-single" tooltip="'.$tt_gemeubileerd.'">gemeubileerd</span>');
return true;
}
add_filter('wordfilter','word_filter');
I need this to run on every page in the website, replacing all the words with the same word, but inserted in a span. Doing so will allow a tooltip to appear when I mouse over the word.
The mouseover and tooltip already work, but I can't figure out how to get the replace to work on all pages.
How can I best call this function without causing too much page load?
I think you can use javascript split. the code will alert the text, but you can change that and use it for tooltip.
var txt = 'Word*tooltip';
alert(txt.split("*")[1]);

how to skip some words in a paragraph by php

i have a paragraph in the database its like
$str ="this is a paragraph i show shortly and when i click on the view more it will show completely for that i am using the ajax and retrieve it "
i show this like
this is a paragraph i show shortly
php for show the first some word is
function chop_string($str, $x)// i called the function
{
$string = strip_tags(stripslashes($string));
return substr($string, 0, strpos(wordwrap($string, $x), "\n"));
}
and when user click on the view more it will display rest of it but the problem it that how to skip this this is a paragraph i show shortly and show the rest of it
i want to show the paragraph after the $x on click on view more
For truncating a string by character of word amount:
This SO question may be of help.
As would this one.
Here's some code that does it specifically by word count.
As far as showing more text on the click of a link goes, what I would suggest is loading the string from the database one time and format it's output. If your string is:
This is whole string pulled from my database.
Then the following code would be formatted like such:
HTML
<p class="truncate">This is the whole string <a class="showMore">Show more...</a><span> pulled from my database.</span></p>
CSS
p.truncate span { display: none; }
That way you can use Javascript (preferably through a library like jQuery which I've chosen for my code below) to hide or show more of your solution without having to make a second database request using AJAX. The following Javascript would do what you're requesting:
$("a.showMore").on("click", function() {
$(this).parent().find("span").contents().unwrap();
$(this).remove();
});
Here's a fiddle to play with!
I have made an example here: shaquin.tk/experiments/showmore.html.
You can view the source to see all of the code behind it. The PHP code is displayed on the page.
If you don't want to display the start string when Show more is clicked, replace the JavaScript function showMore with this:
function showMore() {
if(state == 0) {
state = 1;
document.getElementById('start').style.display = 'none';
document.getElementById('end').style.display = 'block';
document.getElementById('showmore').innerHTML = 'Show less';
document.getElementById('text-content').className = 'expanded';
document.getElementById('start').className = 'expanded';
} else {
state = 0;
document.getElementById('start').style.display = 'block';
document.getElementById('end').style.display = 'none';
document.getElementById('showmore').innerHTML = 'Show more';
document.getElementById('text-content').className = '';
document.getElementById('start').className = '';
}
}
Hope this helps.
Use this function :
function trim_text($string, $word_count)
{
$trimmed = "";
$string = preg_replace("/\040+/"," ", trim($string));
$stringc = explode(" ",$string);
//echo sizeof($stringc);
//echo " words <br /><br />";
if($word_count >= sizeof($stringc))
{
// nothing to do, our string is smaller than the limit.
return $string;
}
elseif($word_count < sizeof($stringc))
{
// trim the string to the word count
for($i=0;$i<$word_count;$i++)
{
$trimmed .= $stringc[$i]." ";
}
if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
return trim($trimmed).'..';
else
return trim($trimmed).'...';
}
}
$wordsBefore = 3;
$numOfWords = 7;
implode(' ', array_slice(explode(' ', $sentence), $wordsBefore, $wordsBefore+$numOfWords));
This will return the first 7 words of a sentence if you save it to a variable named sentence.

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

string in php vs. string in javascript

Here is a simple code I have problem with:
<label id="label1">
<?php
echo "Text inside label1";
?>
</label>
<script language="JavaScript" type="text/javascript">
var text = document.getElementById("label1").innerHTML;
alert(text); // show what's in variable 'text'
if(text == "Text inside label1")
{
alert("I am inside.");
}
else
{
alert("No.");
}
</script>
The problem is that the first alert is showing "Text inside label1"(as it should do) but the second one is showing "No.". When I tried to write text right into html (not through php), it worked fine => the second alert showed "I am inside.". I have no idea what problem is there. Could there be the problem with some differences between string types (php vs. JS) or something like this?
Thanks for any ideas
There is a space at the beginning of the text in the label (all whitespace in HTML is collapsed into one space), but not at the beginning of the string you're comparing it with.
Your PHP code:
<label id="label1">
<?php
echo "Text inside label1";
?>
</label>
...will get sent to the browser like this (PHP will strip the line break after the ?> for you):
<label id="label1">
Text inside label1</label>
...which is just like
<label id="label1"> Text inside label1</label>
(Note the space.)
So this should fix it:
<label id="label1"><?php
echo "Text inside label1";
?></label>
JavaScript has no knowledge of PHP. There is no difference of types or anything. The page that is output is the page that is output. Look at the difference between doing it statically and via PHP.
I suspect you're having an issue with the whitespace surrounding the text you're echoing.
The innerHTML in your example seems to contain a line break:
<label id="label1"> <-- Line break
<?php
echo "Text inside label1";
?> <-- PHP strips this line break
</label>
That's why text == "Text inside label1" doesn't match. Try instead:
<label id="label1"><?php echo "Text inside label1" ?></label>
The problem is, that text contains also the linebreaks and whitespace inside #label.
This works as expected:
<label id="label1"><?php
echo "Text inside label1";
?></label>
<script language="JavaScript" type="text/javascript">
var text = document.getElementById("label1").innerHTML;
alert(text); // show what's in variable 'text'
if(text == "Text inside label1")
{
alert("I am inside.");
}
else
{
alert("No.");
}
</script>
The issue with this may be that the label contains extra spaces and new line characters. The better approach maybe indexof:
var str = "Text inside label1";
if(str.indexOf(text) != -1)
{}
As said below, the problem is the spacing of a new row.
You can fix that by either doing
<label id="label1"><?php
echo "Text inside label1";
?></label>
Or you could just trim the string with jQuery.trim, or add your own prototype such as
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
myString.trim();

javascript limit display link from text area

i have a following feed from twitter and im making all links clickable and then i want that links which are inside a tag to be short to 30 chars, if its more then 30 chars then show ... after 30 chars
twitter feed
i need to start learning some real javascript from http://javascript.com/java/codes/snippet/search?q=javascript+limit+chars+leading some more text here, so dont remove this.
TO
i need to start learning some real javascript from http://javascript.com/java... some more text here, so dont remove this.
just need to know how can i truncate the inside of tag.
Edited
the link can be anywhere in whole text area.
To truncate a string, have a look at the trunc-prototype method for strings in my answer here. To acquire all links of a page use:
var linksHere = document.getElementsByTagName('a');
loop through your links and shorten the innerHTML of every link if the length is more than you want. Something like:
var i=-1,len = linksHere.length;
while (++i<len){
linksHere[i].innerHTML = linksHere[i].innerHTML.trunc(30);
}
Here's a handy truncating function I use.
// Examples
truncate('abcdefghijklmnopqrstuvwxyz'); // returns 'abcdefghijklmnopqrst...'
truncate('hello there', 15); // returns 'hello there'
truncate('hello there', 5, '...read more...'); // returns 'hello...read more...'
// Truncating method
function truncate(string, length, end)
{
if (typeof length == 'undefined')
{
length = 20;
}
if (typeof end == 'undefined')
{
end = '...';
}
if (string == null)
{
return '';
}
return string.substring(0, length-1)+(string.length > length ? end : '');
}

Categories