jQuery .html() not executing embedded jquery - javascript

I've scrolled through most of the questions in stack overflow and also Google and tried out a bunch of codes but still can't seem to get my code to work!
So what I'm trying to do is to get some text and scripts via Ajax and insert them onto a div, however, the inline jQuery doesn't seem to work. The text can be very long, so what I wanted to do was add a preview of the text, and when the user clicked a "See more" link, the jQuery toggled the longer text to display and hide the preview.
Here is my code that inserts text into the document;
JSON returned from Ajax
if (resp['marker'].length > 0) {
htmltext = '<h5>Markers<a class="pull-right" onclick="seeall(\'marker\')">See all</a></h5><hr>';
for (var i = 0; i < resp['marker'].length; i++) {
htmltext += '<p><a>'+resp['marker'][i]['title']+'<a class="label label-warning"> > Go to marker</a></a></p>';
htmltext += '<p id="marker-prev'+i+'"><span>'+resp['marker'][i]['advertisement'].substring(0,50)+'</span><a onclick="$(\'#marker-all'+i+'\').toggle();$(\'#marker-prev'+i+'\').toggle()"> More </a></p>';
htmltext += '<p style="display:none" id="marker-all'+i+'"><span>'+resp['marker'][i]['advertisement']+'</span><a onclick="$(\'#marker-all'+i+'\').toggle();$(\'#marker-prev'+i+'\').toggle()"> Less </a></p>';
htmltext += '<p><span>'+resp['marker'][i]['catagory']+'</span></p>';
}
htmltext += '<hr>';
$('#markerssr').show();
$('#markerssr').html(htmltext);
}
funny thing is, several lines down, THIS code works;
JSON returned from Ajax call
if (resp['corp'].length > 0) {
htmltext = '<h5>Businesses<a class="pull-right" onclick="seeall(\'corp\')">See all</a></h5><hr>';
for (var i = 0; i < resp['corp'].length; i++) {
htmltext += '<p><a>'+resp['corp'][i]['name']+'</a><a class="label label-warning"> > Go to business</a></p>'
htmltext += '<p id="corp-prev"><span>'+resp['corp'][i]['description'].substring(0,50)+'</span><a onclick="$(\'#corp-all\').toggle();$(\'#corp-prev\').toggle()"> More </a></p>';
htmltext += '<p style="display:none" id="corp-all"><span>'+resp['corp'][i]['description']+'</span><a onclick="$(\'#corp-all\').toggle();$(\'#corp-prev\').toggle()"> Less </a></p>';
htmltext += '<p><span>'+resp['corp'][i]['address']+'</span><span>'+resp['corp'][i]['email']+'</span></p> ';
}
htmltext += '<hr>';
$('#businessessr').show();
$('#businessessr').html(htmltext);
}
Sorry my code is horribly formatted, but I am on a deadline.

The first thing I see (but it probably is nothing new), is that there are different ID's called from within the inline jQuery.
$(\'#marker-all\').toggle() VS $(\'#corp-prev\').toggle().
Also, are you sure there is only 1 #marker-all on the page? jQuery will stop searching after it has found the first ID.
When you run the following code in the browser console:
$('#marker-all').length
Does it output 1? Or 0?

Related

Why can't I add to innerHTML? [duplicate]

document.getElementById("outputDiv").innerHTML = "";
document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
document.getElementById("outputDiv").innerHTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
document.getElementById("outputDiv").innerHTML += "</tr></table>";
I want to draw a table using Javascript.
So I wrote the code like above.
I think it draw one row that has 10 columns, but it doesn't work.
Anyone know about this problem???
I ran into this problem years ago, too.
The problem is that when you use the innerHTML property to add HTML, after each update, the underlying engine will close unclosed tag (and fix other bad HTML) for you. So after the second line, the <table> and <tr> tags are automatically closed and all content after that will just be written outside the table.
Method 1
(The easy way)
Use a string to store the HTML for the whole table and update it all at once.
var HTML = "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
HTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
HTML += "</tr></table>";
document.getElementById("outputDiv").innerHTML = HTML;
​
Fiddle
Method 2
(The better way)
Use DOM functions
var table = document.createElement('table');
table.setAttribute('border','1');
table.setAttribute('width','100%')
var row = table.insertRow(0);
for(j=1; j<=10; j++){
var text = document.createTextNode(String.fromCharCode(j+64));
var cell = row.insertCell(j-1);
cell.setAttribute('align','center')
cell.appendChild(text);
}
document.getElementById("outputDiv").appendChild(table);
Fiddle
Method 2 enhanced
(The yet better way)
Use CSS instead of HTML attributes. The latter is generally depreciated as of latest specs.
A great resource to start learning CSS is the Mozilla Developer Network
Fiddle
Method 3
(The long way, but the best in the long-run)
Use jQuery.
$('<table>').append('<tr>').appendTo('#outputDiv');
for(j=1; j<=10; j++)
$('<td>').text(String.fromCharCode(j+64)).appendTo('tr');
Fiddle
I think the main problem is that your attributes are not quoted.
But it's almost always a bad idea to repeatedly update the content of a dom element in a loop—each time you update dom content it causes some internal work to be done by the browser to make sure the page layout is current.
I would build the html string up locally, then make one final update when done. (and of course make sure your attributes are quoted)
document.getElementById("outputDiv").innerHTML = "";
var newTable = "<table border='1' width='100%'><tr>";
for(j = 1; j <= 10; j++) { //opening braces should always be on the same line in JS
newTable += "<td align='center'>" + String.fromCharCode(j+64) + "</td>";
}
newTable += "</tr></table>";
document.getElementById("outputDiv").innerHTML = newTable;

Keep Jquery accordion menu open on current page

I am sure that i will get help in my particular case. No doubt there are many solutions to achieve this but in my case I am unable to achieve it.
Following is my code to generate html dynamically using java script.
Edit 1: I just want to keep open the current pan of accordion as per href attribute of anchor tag which is in fact current page URL. This is it.
JS code to generate html:
<script>
$.ajax({
url: "/categories",
type: 'GET',
success: function(data) {
var content = "";
content += '<div id="category-navigation">';
for (i = 0; i < data.length; i++) {
content += '<div class="head">';
content += '<label class="categoryLables">' + data[i].title;
content += '</label>';
content += '<div>';
content += '<div class="boardsMargin">';
content += '<ul>';
for (j = 0; j < data[i].assigned_boards.length; j++) {
content += '<li>';
content += "<a href='/#categories/" + data[i].id + "/boards/" + data[i].assigned_boards[j].id + "'>";
content += data[i].assigned_boards[j].name;
content += '</a>';
content += '</li>';
}
content += '</ul>';
content += '</div>';
content += '</div>';
content += '</div>';
}
content += '</div>';
$("#myNavigation").html("");
$("#myNavigation").html(content);
$('.head').accordion({
heightStyle: "content",
active: true,
collapsible: true
});
}
});
</script>
HTML:
<div class="myNavigation">
</div>
Edit 2: For more clear view, this is picture of my accordion.
As a side note: I am working in ruby 2.2.1 and rails 4.1
You can use localStorage like so:
$(function () {
$("#accordion").accordion();
if (localStorage.getItem('active') != null) {
$($('h3').get(parseInt(localStorage.getItem('active')))).trigger("click");
}
});
$('h3').click(function () {
localStorage.setItem('active', $(this).index("h3"));
});
Here is the JSFiddle demo :)
Note: You may also want to read about sessionStorage
Try setting active option in accordion to the index of panels you want to keep open i.e 0,1,2 etc and set collapsible to false
As per the docs:
Integer: The zero-based index of the panel that is active (open). A negative value selects panels going backward from the last panel.
Reference: http://api.jqueryui.com/accordion/#option-active
JS:
$('.head').accordion({
heightStyle: "content",
active: 1, //Change this
collapsible: false
});

Problems with javascript print function

I have this javascript code to print html table from a PHP document.
function printReport()
{
var data = '<input type="button" value="Print this page" onClick="window.print()">';
data += '<input type="button" value="Close this page" onClick="window.close()">';
data += '<table border="0"';
data += $('#reportTable').html();
data += '</table>';
myWindow=window.open('','','scrollbars=yes,resizable=yes,width=500,height=400');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
};
It opens the new windows, displays the content right, the close button works fine, however the print button doesnt work.
My printer is working properly, I printed from word or any other app and works fine.
My problem is: the print function window.print() is NOT working.
If anyone could give me a hand, would be appreciated.
Cheers
Change:
data += '<table border="0"';
to
data += '<table border="0">';
and tell us the net result. Tested with simple HTML content within the table. Assuming your .html() call returns valid table data, the window should be printable now.
Working fiddle here: http://jsfiddle.net/aV85r/

Copy div to a popup

How can I copy an entire div to a popup window?
What I`m trying to do:
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript' />\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
text += $("#divDadosBasicos").html($(querySelector).html());
text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n/body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
I dont know if this is the better way to do it. If you think/know a easier way to do it, please share
Thanks in advance!
Fix some of these errors and it will work fine
Script tag is not closed properly
body tag not closed properly
querySelector is not defined. (I am commenting that portion)
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript'></script>\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
//define querySelector
//text += $("#divDadosBasicos").html($(querySelector).html());
//text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n</body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
You could use a Jquery Modal Popup
http://jqueryui.com/demos/dialog/
Check it out, it has the functionality that you need.
It has several events you can tweak to modify the data.
Just tested this, and the code seems to be working just fine as long as querySelector is defined, and it's in a document.ready function and you are testing this on an actual webserver (like WAMP/LAMP etc.). It will not work in places like jsFiddle etc.

Programmatically creating <DIV>s and problems arise

I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S
the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)
function createPlayGround(rows, who)
{
$('#container').hide();
var grid = document.getElementById("Grid" + who);
var sqnum = rows * rows;
var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
innercode += '<tr>';
for (i=1;i<=sqnum;i++)
{
var rowno = Math.ceil(i / rows);
var colno = Math.ceil(i - ((rowno-1)*rows));
innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
if (i % rows == 0)
{
innercode += '</tr><tr>';
}
}
innercode += '</tr></table>';
grid.innerHTML = innercode;
$('#container').fadeIn('slow');
}
It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":
<div id="whatever" onclick="function(this)"></div>
If you're actually more interested in getting the id of the div clicked on, you can do this:
<div id="whatever" onclick="function(this.id)"></div>
However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.
Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:
$("<div></div>")
.click(function(e) {
selectTarget(i, who);
})
.appendTo(container);

Categories