How to share jQuery .data() data through iframe's? - javascript

I'm trying to share jQuery data from one or more iframe'd html pages with their parent html document.
What I need is an inter-iframe communication and if possible (highly desireble) to share/exchange .data() i.e. the $.cache of both jQuery objects (in the parent and child iframe).
Someting similar to this:
Parent html:
<!DOCTYPE html>
<html>
<head>
<title >iframe-data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
var testData = 'hello world from #div1';
$('#div1').data('test',testData);
var newTestData = $('.div2').closest('.div1').data('test');
$('#div2').append( 'Parent window: "' + testData + '" === "' + newTestData + '" => ' + (testData === newTestData) );
}); // jQuery()
</script>
</head>
<body>
<div id="div1" class="div1" >
<div id="div2" class="div2" >
</div>
<iframe src="iframe-data2.html" ></iframe>
</div>
</body>
</html>
Iframe html:
<!DOCTYPE html>
<html>
<head>
<title >iframe-data2</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
var testData = 'hello world from #div1';
var $body = $(window.top.document.body);
var $div1 = $body.find('#div1');
var outsideTestData = $body.find('#div1').data('test');
var $div2 = $('#div2');
$div2.append( 'outside test data: "' + testData + '" === "' + outsideTestData + '" => ' + (testData === outsideTestData) );
}); // jQuery()
</script>
</head>
<body style="background-color: silver">
<div id="div1" class="div1" >
<div id="div2" class="div2" >
</div>
</div>
</body>
</html>

jQuery object itself is created inside anonymous function and it uses closure for accessing global (global for other jQuery functions) array inside this functions. So, as result: jQuery in iframe and jQuery in the top window have different data array. If you need top level data, use window.top.jQuery('#div1').data('test1') (please note that default context for jQuery is document, where it was initially created, so using "top level jQuery" we don't need to specify top level document.

Have a look at Ben Alman's jQuery postMessage plugin

Related

Javascript always return null when I try to get content from asp.reportviewer

I want to print reportviewer content directly without save as pdf, excel or word. After searching from Google, there is a solution like code below:
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body></html>";
var newstr = document.getElementById(printpage).innerHTML;
var oldstr = document.getElementById("body1").innerHTML;
document.getElementById("body1").innerHTML = headstr + newstr + footstr;
window.print();
document.getElementById("body1").innerHTML = oldstr;
return false;
}
<div id="body1">
<input name="b_print" type="button" class="ipt" onclick="printdiv('div_print');" value="Print" />
<div id="div_print">
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="944px" ShowPrintButton="true" SizeToReportContent="True" AsyncRendering="false" ></rsweb:ReportViewer>
</div>
The problem is, it come out error said 'Cannot read property 'innerHTML' of null'.
What had I missing ?
Your javascript code should go last in the body tag. What is happening here is that your javascript is running first but it can't find the element with id body1 since that markup is not in defined yet. You can also define it in the head in a script tag with an src attribute.
It should be like this:
<head>
<script src="my_script.js"></script>
</head>
<body>
<div id="body1"></div>
...
<script type="text/javascript">
function printdiv(printpage) {...}
</script>
</body>

jQuery class selector and text adding

I have two files index.html and star.js.
My index file looks so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="foo">
<h2>First:</h2>
<p>3</p>
</div>
<div class="foo">
<h2>Second:</h2>
<p>5</p>
</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="star.js" charset="utf-8"></script>
</html>
And my js file looks like that:
var element = $(".foo > p");
//Try to figure it out
console.log('First: ' + element.text() + ' second: ' + element.text());
All I want from this code is just log out in the right sequence:
First: 3 second: 5
But my console gives me this:
First: 35 second: 35
I know that $(".%classname%) method looks thought all foo classes in the file but it doesn't return an array. Can I solve my problem somehow?
I need to use jQuery. Not pure js with .getElementsByClassName.
I can't change my classes name. .foo requires.
I need the solution which doesn't depend on number of classes.
The nearest solution I found in :eq() pseudo-selector but is there any other ways?
The text method will return text contents of all the elements present in the jQuery object.
You will have to iterate over the items in the elements then print each one like
var element = $(".foo");
element.each(function() {
var $this = $(this);
snippet.log($this.find('h2').text() + ': ' + $this.find('p').text());
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="foo">
<h2>First:</h2>
<p>3</p>
</div>
<div class="foo">
<h2>Second:</h2>
<p>5</p>
</div>
Try
$('.foo:nth-child(1) p').text()
and
$('.foo:nth-child(2) p').text()
EDIT: going to bring my answer out of fiddle for future reference:
Use a loop to iterate through any number of elements
for(i=1; i <= $('div.foo').length; i++){
$('.output').append($('.foo:nth-child('+i+') h1').text() + ": ");
$('.output').append($('.foo:nth-child('+i+') p').text() + "<br/>");
}

HTML/JS: appendTo doesnt work

I wanted to dynamically append a Table/List to HTML page. My code as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lead Manager</title>
<link rel="stylesheet" href="themes/Bootstrap.css">
<link rel="stylesheet" href="themes/jquery.mobile.structure-1.2.0.min.css" />
<script src="themes/jquery-1.8.2.min.js"></script>
<script src="themes/jquery.mobile-1.2.0.min.js"></script>
</head>
<body id="body" name="body">
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Lead Manager</h1>
</div>
<div data-role="content" data-theme="a">
<h2>List of Leads</h2>
</div>
</div>
</body>
<script>
$(document).ready(function(e) {
//var data = Android.getLeads();
var data = [{"status":"1","name":"1","campaign":"1","date":"1"},{"status":"2","name":"2","campaign":"2","date":"2"}];
var items = [];
var date;
var name;
var status;
//eval(" var x = " + data + " ; ");
//var y = JSON.stringify(x);
$.each(data, function(key,val){
items.push('<tr><td>' + val.date + '</tr></td>');
});
var text = $('<table/>', { html: items.join('')});
$('<table/>', {
html: items.join('')
}).appendTo('body');
});
</script>
</html>
The Items[] variable is getting filled with the tr and td values. However, the appendTo, doesnt work. The JSON as you can see doesnt require eval as its already in the format required.
Please can you help?
The issue was mainly because of the jquery.mobile script as it wasnt allowing dynamic addition of html code.

Dynamically add jquery mobile components to listview with formatting

When I'm dynamically inserting the following code, I can force the page to refresh so it applies the jQuery mobile formatting.
For some reason its doesn't allow me to set the button formatting. Its really odd, because it allows the list to be dynamically inserted and the button, but i cant seem to format the button except for the name.
It can be manipulated via CSS but I want to use the jQuery API.
$('#cartList').append('<li>'
+ '<h3>' + game.Title+'</h3>'
+ '<p>' + '£' + game.Price + '</p>'
+ 'Remove'
+ '<h3 class="ui-li-aside">' + game.Format + '</h3>'
+ '</li>').trigger("create");
The jQuery Mobile Doc mentions that if new list items are added to the list or removed from it, the dividers are not automatically updated and you should call refresh() on the listview to redraw the autodividers.
Try to add: $('#cartList').listview('refresh'); after you have populated the list.
Example:
<!doctype html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script>
$(document).ready(function(){
$("#add-li-button").click(function(){
$('#listList').append("<li data-role=\"collapsible\"> <h3>New List</h3> <div data-role=\"fieldcontain\"></div> </li>").listview("refresh");
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<ul id="listList" data-role="listview">
</ul>
<input type="button" id="add-li-button" value="add a checkbox to list1" />
</div>
</body>
</html>

Custom div loading not working

To those jQuery experts out there. I have the following markup and code:
<html>
<head>
<title>Test Framework</title>
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.nav').click(function(e) {
e.PreventDefault();
var id = $(this).attr('id');
var path = "views/" + id + ".html";
$("#main").load(path);
});
});
</script>
</head>
<body>
<div id="links">
<a class="nav" id="test" href="javascript:void(0);">Test Page</a>
</div>
<div id="main">
</div>
</body>
</html>
My nav class fires when I click the link, but fails to get past the PreventDefault method. The class fires, but nothing loads into my div. The page is definately there. Any ideas why this wouldn't be working?
The problem may be with your call to preventDefault:
$(document).ready(function(){
$('.nav').click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
var path = "views/" + id + ".html";
$("#main").load(path);
});
});

Categories

Resources