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();
Related
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
});
following example:
I got a php function which generates me some text with "\n\r" at the end
The output is generated in a html div, which is hidden
JQuery takes the text of the div with innerText
Writes it in a other div
That's what i do in the moment.
The line break in php has no effect to the "end div".
How can i get the line break at the end div?
Regards
EDIT: With a <br> in my php function an alert works fine. So the failure is at point 4.
var text = document.getElementById("statistiktextdiv").innerText;
$jq( "#statistiktext" ).text(text);
<div id="statistiktext"></div>
function showsomething(){
for($i = 0; $i < count($statistik); $i++){
echo $something[$i]['number'] . "<br>";
}
}
?>
<div id="statistiktextdiv" style="visibility: hidden;"><?php showsomething(); ?></div>
You can use the javascript String.replace method to change the \n\r to a <br> tag so the browser will render it.
alteredText = originalText.replace( '\n\r', '<br>' );
You can see that the console and alert windows treat these special characters the way a text editor does, but they are not rendered as breaks in html.
originalText = "line 1\n\r\line 2";
alteredText = originalText.replace( '\n\r', '<br>' );
console.log( originalText );
console.log( '---------' );
console.log( alteredText );
$('body').append( originalText );
$('body').append( '<hr>' );
$('body').append( alteredText );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Something interessting:
When i write the text from JS to an textarea, its working!
So the problem seems to be the <div>.
I tryed with a random tag like <random>, it's not working.
Any ideas what is wrong?
I have used a Wordpress theme and customiser text print as html tag. I want to print as text like.
704 372 6846
I want to display the "704 372 6846" text with link as we get in the frontend.
I am trying strip_tags() for this. But it is still not working. Where I am doing wrong.
You can use html_entity_decode. It decodes the html tags and shows the text as it is.
According to its documentation:
html_entity_decode — Convert all HTML entities to their applicable characters
So in you case use it like this
<?php
$phone = html_entity_decode("<a href='tel:704-372-6846'>704 372 6846</a>
");
echo $phone;
Let me know if this doesn't work for you.
I assume that You saved the text as HTML format (input) but you want to print it as a link in front end, If this is your question
Then a quick solution for this is to use CSS and JavaScript to hide the text box and show it as Archer tag.
Check for my demo
http://cssdeck.com/labs/imxsreqk
HTML
<div class="inputContainer">
<input class="myInput" type="text" name="myInput" id="myInput" value="704 372 6846" />
</div>
CSS
.inputContainer {
position:relative;
width:100px;
}
.inputContainer input {
display:none;
}
JavaScript
(function () {
var inputval = document.getElementById('myInput').value;
var ancher = document.getElementById('inputAncher');
ancher.innerHTML = inputval;
})();
I am using Javascript to hide / show a blog-post stored in a mysql table. The script for doing this is:
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className = (item.className == 'hidden') ? 'unhidden' : 'hidden';
}
}
</script>
This links to some css styling:
.hidden {
display: none;}
.unhidden {
display: inline;}
I am calling the script via a href styles as a button:
<a class=button href="javascript:unhide('first_post');">More</a>
As for the content I originally tried the following to initially show a small section of text, then the rest after the link is clicked:
<?php $var = mysql_result($result,0,"post_text"); ?>
<?php echo substr($var, 0, 400); ?>
<div id="first_post" class = "hidden">
<?php echo substr($var, 400, 5000)?>
</div>
However where the two sets of sub-strings join there is a space. For example if the first sub-string ends in "the tree's hav" and the second sub-string starts "e eyes you know" the concatenation results in "the trees hav e eyes you know"
Can anyone help me with this problem?
Remove newlines between <?php ?> and <div> tags - this should help you get rid of spaces.
<?php echo substr($var, 0, 400); ?><div id="first_post" class = "hidden"><?php echo substr($var, 400, 5000)?></div>
I think what you're looking for is you want to truncate string from the end of the word rather than giving link somewhere in between. That's what I see as permanent solution...
When I googled up expecting that PHP would have something available out of the box found following 2 article which might help you.
http://css-tricks.com/snippets/php/truncate-string-by-words/
How to Truncate a string in PHP to the word closest to a certain number of characters?
They are not exactly what you're looking for but they can be of great help if you take inspiration from the concepts.
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).")\">";