I have a HTML page which has one div and table. Then I have a PHP script which sould print the HTML for a table. Anyway, the table will not be modified. Does my print command include some kind of special charasters or is there something else which could be the reason?
I have a file index.html with the following jQuery code:
$(document).ready(function(){
setInterval(function() {
var kaavio = 106;
jQuery.post("search.php", {
kaavio: kaavio
}).done(function(data) {
$('#check').html(data);
});
}, 6000);
});
Here is the HTML of the file index.html:
<div id="check"></div>
<table id="paikka59"></table>
I also have a PHP file search.php and here is the code of it:
print "<script>document.getElementById('paikka59').innerHTML = '<tr><td class=\"pisteet\" style=\"border-top:2px solid #16B2B4;padding:0\"></td><td class=\"nimi\" style=\"border-top:2px solid #16B2B4;padding:0\">2888 Salmi Risto</td><td class=\"tasoitus\" style=\"border-top:2px solid #16B2B4;padding:0\"></td></tr> <tr><td class=\"pisteet\" style=\"padding:0\"></td><td class=\"nimi\" style=\"padding:0\">2893 Rantanen Mikko</td><td class=\"tasoitus\" style=\"padding:0\"></td></tr> <tr><td class=\"pelimuoto\"><!-- a --></td><td class=\"ajankohta\"><!-- b -->Pöytä -Ei aikataulutettu</td><td class=\"toiminnot\"><!-- c --></td></tr>');</script>";
1st, I didn't go further than the first mistake (in comments)
print "<script>alert('<tr><td class="pisteet" style="border-top:2px solid #16B2B4;padding:0">
-> just this line should throw an error
You really need to use a decent IDE :)
your code shows :
print "<script>document.getElementById('paikka59').innerHTML = '<tr>
<td class=\"pisteet\" style=\"border-top:2px solid #16B2B4;padding:0\"><!-- a --></td></tr>');</script>";
you should get rid of the extra ) at the end
when testing, throws a warning/error
See Element.innerHTML for different Syntax
EDIT: always check all of the stuff, especially looooong ones :)
double quotes are creating a problem here.
Your print string is getting terminated at
print "<script>alert('<tr><td class=" // rest all code will be skipped
Use \" in such situation. Your print statemnet will become like
print "<script>alert('<tr><td class=\"pisteet\" ... </tr>');</script>";
One more thing, you can not add html tags inside alert(). You can only insert plaintext to alert(), confirm() and prompt() boxes.
Have a look at below thread :
HTML Tags in Javascript Alert() method
Related
Edit : I would like to rephrase my question
I am simple trying to get anchor tag text inside <td> on checkbox check.
Problem is that anchor tag doesn't have id or class
This is a sample of my table
<table class="wp-list-table widefat fixed striped users">
<tbody id="the-list" data-wp-lists="list:user">
<tr id="user-18">
<th scope="row" class="check-column">
<label class="screen-reader-text" for="user_18">Select abc</label>
<input type="checkbox" name="users[]" id="user_18" class="subscriber" value="18">
</th>
<td class="username column-username has-row-actions column-primary" data-colname="Username">
abc
</td>
</table>
I have searched some post and tried to create some function
<script type ="text/javascript">
$('#changeit').click(function(){
var values = [];
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
});
alert($(row).find("a")[0]);
});
</script>
this gave me anchor tag href data, but I need text enclosed in anchor tag.
I tried
alert($(row).find("a")[0].text());
alert($(row).find("a")[0].val());
alert($(row).find("a")[0].val);
But they are not giving me the anchor tag text.
Any suggestion will be helpful.
Try this:
function Bindthis() {
$('#changeit').on('click', function() {
alert('1'); //this is hitting
var values = [];
$('.subscriber').attr('checked', true).each(function() {
alert('2');
row = $(this).closest("tr");
});
});
}
This is easily traceable by following some good coding practices.
First, you need your code well indented. Indentation is a must if you want to write good, clean and error free code. Error free because indentation helps a lot to identify different scopes.
Second, ALWAYS look for logs. I know that you don't look for logs because you use alert() instead of console.log(), and also, if you open the console (F12) with your code, you will notice this error:
Uncaught Error: Syntax error, unrecognized expression: #the-list input[name=users[]]:checked
With this, is easy to understand that the selector syntax is wrong. Searching a bit around internet and learning about selectors, you will notice that the syntax needs some quotes, like this #the-list input[name='users[]']:checked.
Seems that you don't understand well how selectors work, so, to avoid this problem and future ones, I recommend you to read a bit about them. This way you will avoid repeating the same selectors questions here. Here is a good reference website, with an online tester: http://www.w3schools.com/cssref/css_selectors.asp
finally I made this code which is working for me
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
anchor = $(this).closest('tr').find("a:first");
});
alert($(anchor).text());
I have some HTML that looks like this:
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
**Text I want to modify**
<span>more content</span>
</td>
targetTD iterates a dynamic number of times depending on the content being rendered. For each iteration, I need to remove a substring of ": " from the beginning of the code in the text block. Unfortunately it's not in its own element and I don't have the ability to wrap it in a neat and tidy id/class. I did some searching and found some js I thought might do the trick:
<script>
var myString = $('.targetTD').html();
myString = myString.replace(': ','');
$('.targetTD').html(myString);
</script>
But that spits out a console error:
Unable to get property 'replace' of undefined or null reference.
Final Update (Solution)
Thanks to #Vaibhav for coming up with a fix! This script did the trick:
<script type="text/javascript">
$(function() {
$('.targetTD').each(function () {
$(this).html($(this).html().replace(/\:\s/g, ''));
});
});
</script>
Update 1
Thanks to #BenM I was able to stop the error from producing by using the following code:
<script>
$(function() {
$('.targetTD').html(function() { $(this).html().replace(': ', ''); });
});
</script>
Although I now don't get an error message, this still isn't removing the ": " from the text block. Any ideas on why this might be?
Update 2
To provide some SharePoint specifics broadly, in response to a comment from #ElvisLikeBear:
The specific task I'm trying to accomplish is hiding the column name from a grouped by list. In SP2010 this was easy to do by hiding the ms-gb class. In 2013, Microsoft has lumped in the expand/collapse button with this class so hiding it wholesale is not an option. I've successfully hid the span with the column name (in my code above, the span wrapped in the a), but the ": " is unhelpfully still in the text block, and now it's just floating there at the beginning of each category name.
The code is being deployed at the page level as a snippet, using the Script Editor web part.
Brendan, issue with your code is you are replacing the ':' with '' but you are not assigning it to the same td again.
Replace(':','') function replaces only first occurance of ':'.Please follow my code. it will replace all the ':' with ''.
With reference from "targetTD iterates a dynamic number of times depending on the content being rendered"
I assume you need foreach loop to iterate over all the Tds.
Html :-
<table>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1
<span>more content</span>
</td>
</tr>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1:test2
<span>more content</span>
</td>
</tr>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1:test3:test4
<span>more content</span>
</td>
</tr>
</table>
Jquery :-
<script type="text/javascript">
$(function() {
$('.targetTD').each(function () {
$(this).html($(this).html().replace(/\:/g, ''));
});
});
</script>
Script is tested and works fine.
Make sure the DOM is ready:
<script>
$(function() {
$('.targetTD').html(function() { $(this).html().replace(': ', ''); });
});
</script>
Your tag indicates that this is executing on a SharePoint site which is why your code isn't firing. You need to deploy it properly for SharePoint.
You can do this in a solution or feature, or if it's a one page script you should use a script web part (called the Content Editor webpart in SharePoint 2010 and 2007), you could also add a code snippet to the page in SharePoint 2013.
You could also add the script into the tag via SharePoint designer however I do not believe that would be best practice except in some very specific scenarios (however it would be the easiest approach for a non-SharePoint Devleoper).
I've been working on this code for a while. The idea is to get javascript to make a div visible based on the results of a HTML form (not on this page). However, my javascript function never works. I've isolated the problem to the script not being called in the first place. Here's my code:
<!DOCTYPE HTML>
<html>
<body>
<?php
While ($result=mysql_fetch_array($data)){ //I have mySQL code before this
$equipment= $result['safety equipment'];
$equipment2= str_replace(' ', '_', $equipment); //modified equipment name without spaces so that post can read it
$problem = $_POST[$equipment2];
?>
<div style="display:none;" id="<?php echo $equipment?>"> <!--Code that creates a div for each equipment -->
<h1>Report a problem</h1> <br>
You reported that there is a problem with the <?php echo $equipment." in ".$name;?>.<br>
Please describe the problem.
<form>
<textarea row="5" column="300" name="Issue">
</textarea>
</form>
</div>
<?php
if ($problem=="working"){
inspectRoom($UID,$equipment,null);
}else {
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
}
}
?>
<script type="text/javascript">
function Appear(equipment){
alert("hi"); //error trapping
document.getElementById(equipment).style.display='block';
}
</script>
</body>
</html>
$equipment is a string with the name of the equipment (ex: Fume Hood)
$problem is a string retrieved from the previous page. It too has the name of some equipments.
In my console I get the following error:
"SyntaxError: missing ; before statement"
What am I doing wrong?
You're dumping PHP-based text directly into a Javascript context, which is highly dangerous. Any JS metacharacters (especially ') will cause syntax errors and kill the entire JS code block.
echo'var test ='.$equipment.';';
Should be
echo 'var test = ', json_encode($equipment), This will produce syntactically valid JS code, no matter what's in `$equipment`.
Plus, you have MANY other syntax errors. Your php while is NOT contained in a <?php ... ?> code block, so it'll appear directly in your output as raw text. The html inside your while loop is now considered part of the PHP code, so that'll be yet another syntax error. etc... etc... etc.. In other words this code is utterly broken.
Talking solely about javascript since that's what your question is about, your Appear function would never been defined yet since the PHP code would have echoed out the JS that calls Appear before the function is defined.
It is not working because you are forgetting the space after echo. There are other errors also such as your while is not within tags.
For this part of the code
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Replace it with
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo"var test ='$equipment';";
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Th variable isn't surrounded by quotes when the value will be a string;
To start with you are missing a > on line 6.
When I put SMARTY variable between {literal}{$txt_more}{/literal} in Jquery then in source code it display right text (více without quotes) but in console it show this error:
ReferenceError: v\u00EDce is not defined - this error I thought is because it is not in quotes
but when I put it into quotes {literal}'{$txt_more}'{/literal} it show in source code as 'více' but not display as text between tags strong with class show_text (tags are empty inside). Can you help me ? Thank you very much.
Jquery with SMARTY:
$('.show_text').text({/literal}'{$txt_more}'{literal}); // verison with quotes is without error but still not display text between tags with class show_text
$('.show_text').text('show more'); // with show more typed it displays as it should on website
HTML:
<a href="#">
<strong class="show_text" style=" margin-top: 5px; text-align:center; overflow:hidden;white-space:nowrap;position:absolute; z-index:2"></strong>
<img style="position:relative;" class="cond-arr" src="/css/showmore.png" alt="show_more" />
</a>
Wrong quoting, should be:
$('.show_text').text("{/literal}{$txt_more}{literal}");
If you're using Smarty 3, you don't need {literal} anymore, just make sure that there is always a space after any { in your code
If using smarty 2, you don't need to be so specific with literal, remember that the problem is only when there is a "{". Your code will look much cleaner with one of this solutions:
{/literal}
$('.show_text').text('{$txt_more}');
{literal}
or using a javascript variable at the start of your code and surrounding everything else with literal just to be safe
txt_more='{$txt_more}';
{literal}
...
$('.show_text').text(txt_more);
...
{/literal}
I make a jQuery get call to fetch a html fragment and do some processing based on that data
$.get($('.more a').attr('href'), function (data) {
var $data = $(data);
// other code using $data
});
Here, 'data' is
<div class="topDiv"> Data goes here </div>
But $data shows as
<div class="topDiv"> </div>
Only the html tags are shown, while the text inside is not. IE has the same problem(?). However, Firefox parse it correctly.
When I alert($(data).html()) , Firefox shows the alert with proper html while chrome and IE show it with the missing text.
Since I am running my project on localhost I am unable to provide a URL for the html fragment.I am using an asp.net ashx handler to provide the html fragment. Basically, when we post a request to the handler, it returns a html fragment based on a query string parameter passed to it.
String content = "<html> <head> </head> <body>"+
"<div class="topDiv"> Data goes here </div>"+
"</body></html>";
context.Response.ContentType = "text/html";
context.Response.Write(content);
Resolved
As mentioned in the answers, the 'html' fragment was not well formed. Firefox 3 seemed to accept it while Firefox 4, Chrome and IE did not.
I suspect it's because <div>text</div> isn't really a valid html document in itself. IIRC, divs are only supposed to contain block level elements. Text should be inside p, a, etc. So IE and Chrome are killing the text according to DOM standards, Firefox is letting it fly. Tell jQuery the dataType of what you're getting is "text" instead, then insert the content into your div using html(textData) instead.
EG:
$.ajax($('.more a').attr('href'), {
dataType: 'text'
}).done(text) {
$('container selector').html(text);
});
How did this:
String content = "<html> <head> </head> <body>"+
"<div class="topDiv"> Data goes here </div>"+
"</body></html>";
ever compile with the unescaped quotes? If you fixed this, you should be rocking and rolling.