localstorage to send value to a file in iframe - javascript

File 1 has the following script in it:
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') ;
localStorage.setItem("imgid",selected);
var varmodal = document.getElementById('myinfomodal');
var span = document.getElementsByClassName('infoclose')[0];
varmodal.style.display = "block";
span.onclick = function() {
varmodal.style.display = "none";
}
}
The above script opens the following div/iframe (also in File 1):
<div id="myinfomodal" class="infomodal">
<div class="infomodal-content">
<button class="infoclose">Close</button>
<iframe id="frameid" src="https://outzeal.com/zp2.php" width="100%" height="500px;" style="border:none;"></iframe>
</div>
</div>
The variable selected is supposed to be transferred through localStorage to a second file. The script in the second file is:
window.onload = function () {
var a = localStorage.getItem("imgid");
document.getElementById("demo").innerHTML = a;
if(a == 0){
document.getElementById("demo").innerHTML = "no image selected";
}
}
Please click on this link (not available anymore) for a demo. After clicking on the image the image opens in a modal div. Selecting the check box and clicking on the "Cart icon" opens the div and the iframe file but does not show the value of the variable selected (probably because the function should run after window.onload happens and that has never happened here). If the second file is opened separately (window.onload happens here) the value is shown. I want the value of selected in the modal div. How can that be done? Thanks.

Your code has nothing wrong, it's just a cache problem: I copied your code on my local, of course using zp2.html instead zp2.php (I don't have a PHP server) and it seems to works pretty good: I've got both "no image selected" and "skiing/001", instead on the remote I don't see anything (I think it's because a previous behaviour of zp2.p.
Try to edit your zp2.php and use anonymous navigation, or disable the cache on your browser.
PS: Anyway if you change the value of the checkbox after push the button, the iframe will show the first value because you're using window.onload on zp2.php... If you need a popup you don't need to use iframe and another server page, neither localweb, you can use a global javascript variable.

Related

Jquery finds no elements after click unless first alert

Using the Firefox browser console I'm trying to select an element in an i-frame. The i-frame is shown in a modal dialog which opens when I click a link.
This example code below does the following:
Click the first link on page which opens a modal dialog
Show alert
Once I close the alert, the code finds all span elements with class
Code then prints the number of span elements found.
This code works at this link:
https://www.sec.gov/edgar/search/#/q=%2522food%2520and%2520drug%2522
$('.preview-file').eq(1).trigger('click');
alert("close this alert");
previewFrame = $('#ipreviewer');
all = $(previewFrame).contents().find(".sect-efts-search-match-khjdickkwg");
console.log($(all).length);
But, when I take out the alert("close this alert"), the code no longer works. Without the alert the code does not find any span elements and prints 0 to the console.
nonworking code (returns 0):
$('.preview-file').eq(1).trigger('click');
previewFrame = $('#ipreviewer');
all = $(previewFrame).contents().find(".sect-efts-search-match-khjdickkwg");
console.log($(all).length);
Why doesn't this code work without the alert? How can I fix this?
Edit:
I tried a while loop to see if I had to wait for something to load, but it also did not work (never-ending loop).
$('.preview-file').eq(i).trigger('click');
previewFrame = $('#ipreviewer');
all = $(previewFrame).contents().find(".sect-efts-search-match-khjdickkwg");
console.log($(all).length);
while($(all).length < 1){
previewFrame = $('#ipreviewer');
all = $(previewFrame).contents().find(".sect-efts-search-match-khjdickkwg");
console.log($(all).length);
}
The iframe doesn't exist on initial page load
Here's an approach you can play with that uses setInterval() to check for existince of the iframe and items inside the iframe that for me is returning a count of four items found
const timer = setInterval(function(){
const $frme=$('#ipreviewer');
// check if frame exists
if($('#ipreviewer').length){
const $items = $frme.contents().find(".sect-efts-search-match-khjdickkwg");
// check if items found
if($items.length){
// do something with the items
console.log('Found ', $items.length, ' items');
// clear interval timer when found
clearInterval(timer)
}
}else{
console.log('Not found')
}
},100)// 1/10th second intervals
$('.preview-file').eq(1).trigger('click');

Hiding a div container including php generated content with a script

I'm currently working on a website which has a search engine including advanced search options with filters. I want to hide the filters until a category has been chosen. I'm not sure if that script would even work within the php file, because I also tried the script with simple alerts but it didn't work. I positioned this script at the end of the php file of the advanced search options.
<script>
if (document.getElementById("main_cat").value == "-1")
{
document.getElementById("custom_fields").style.display = "none";
}
else
{
document.getElementById("custom_fields").style.display = "inline";
}
</script>
custom_fields is the id of a div container which displays all the filters with php generated content. main_cat is the id of the category, if the value is -1, no category is chosen.
I'm working on a website with wordpress if that is important to know.
Thanks for your help!
I think you have a minor semantic error that's causing your script to not function as expected. Also, to achieve the functional behaviour for the <select> you will need to do a few extra things, namely, to listen to the change event:
<script>
// Store variables to elements we want to work with
var mainCat = document.getElementById("main_cat")
var customFields = document.getElementById("custom_fields")
// When the website first loads, hide "custom_fields" by default
customFields.style.display = "none";
// When the user changes the main_cat select, check it's value. If
// value == "-1" then hide custom_fields. Otherwise display custom
// fields as inline
mainCat.addEventListener("change", function() {
if (mainCat.value == "-1")
{
customFields.style.display = "none";
}
else
{
customFields.style.display = "inline";
}
})
</script>
As a final note, I saw that the script was actually commented out on your website. Just below the <!--Script Custom Fields-->, the script was enclosed in /* ... */ - remove those to ensure that the script does run, rather than be ignored by the browser.
Hope this helps!

Is This Possible in a Browser? [JavaScript / HTML]

I have Javascript code that opens ISBNs of books on Amazon using hyperlinks (feel free to try, for example: 0133098648). I would like the URL to open up on a new window with all links clicked in a new tab on that same window. It appears one can only open in a new tab of the current window, or a new window every time.
Is what I am looking to do even possible? I've been reading that something like this is restricted by browsers for security reasons; Maybe there's a work around? I've been pulling my hair out trying to find a solution for this, if I could it would make my life much more easier.
A picture to describe my question: http://imgur.com/a/5lUP4
Please use JSfiddle example: http://jsfiddle.net/mq1efed2 ( Code does not work on Stackoveflow)
<html>
<div><b>ISBN Hyperlinker</b></div>
<textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea>
<div><b>Hyperlinked text:</b></div>
<div id="output" style="white-space: pre"></div>
<script>
//the input box.
var input = document.getElementById('numbers');
var output = document.getElementById('output')
var base =
'https://www.amazon.ca/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:\d\s*?){10,13})\b/gm);
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item.replace(/\D+/g, ''));
container.appendChild(link);
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
handler(); // run on load
</script>
</html>
No, this isn't possible. Web pages cannot dictate whether or not content opens up in tabs or new windows. It's up to the user/browser to decide.
At best, you can open a new window with window.open(), but that doesn't give you control over tabs in a specific window later.

How to pass a value from a parent window to another html page using javascript?

I have 2 windows home.html and result.html.
In home.html I have a <textarea> #txtinput and a <button> #btn.
In result.html I have another <textarea> #txtresult.
On home.html, if I enter a value into #txtinput and click #btn, I want to open result.html and pass the value of #txtinput into #txtresult.
I've tried the below code from another post, which displays the value in the new window's body but won't display it in my element
var myWindow = window.open();
myWindow.document.body.innerHTML = document.getElementById("txtinput").value;
Is it somehow possible in a simple way? I am relatively new to JavaScript, my courses are ongoing now and I am just curious to know the ways to do it. Any detailed help will be very much appreciated!
I hope i need to elaborate the below code
Button on click function in the home page:
function sample(){
//this will set the text box id to var id;
var id = document.getElementById("text_box_id").id;
//the sessionStorage.setItem(); is the predefined function in javascript
//which will support for every browser that will store the sessions.
sessionStorage.setItem("sent", id);
//this is to open a window in new tab
window.open("result.html","_blank");
}
Retrieve the value in result page:
$(document).ready(function(){
//This sessionStorage.getItem(); is also a predefined function in javascript
//will retrieve session and get the value;
var a = sessionStorage.getItem("sent");
alert(a);
});
For more information about sessionStorage
code.google.com/p/sessionstorage/
developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
I have done same thing as above, am getting values in new window that's great, but that values I am getting only in documet.ready() function. So I am not able to use these values in my JSP. once I got values I need to display them in JSP.
I hope this code help you
This should be in home page:
function sample(id) {
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This is another way in the same home page function:
function sample() {
var id=document.getElementById("your_required_id").id;
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This should be in result page:
function sample1() {
var a=sessionStorage.getItem("sent");
alert(a);
}
The id may be your text box id
In result.html, find the Window which opened it, using window.opener and then take your data of interest from that Window.
window.addEventListener('load', function () { // wait for ready
var home = window.opener, txtinput, txtresult;
if (home) {
txtinput = home.document.getElementById("txtinput");
txtresult = document.getElementById('txtresult');
txtresult.value = txtinput.value;
}
}, false);
In home.html, listen for a click on #btn and open result.html
// assuming button exists at invocation time
var btn = document.getElementById('btn');
btn.addEventListener('click', function () {
window.open('result.html');
}, false);
i think that a simple assignment, using the window.opener handle from within the child window, is what you need:
if (window.opener) document.getElementById("#txtresult").value = window.opener.document.getElementById("#txtinput").value;

Initialize media player only if query string parameter is present

I have a SharePoint page that has a hyperlink which points to a video clip. Clicking on the link will play the video in an overlay window (uses Silverlight). If Silverlight runtime is not present, it displays the "install Silverlight" prompt. When the page is invoked with a IsDlg=1 query string, the hyperlink is hidden (it is in the left navigation bar), and only the main content page is shown. But I still get the "install Silverlight" prompt. I want to get rid of the prompt when IsDlg=1 is present.
Below is the relevant javascript code on the page. I've modified it slightly to initialize the media player only if IsDlg=1 is not present. But it is not working as expected. Any ideas?
// original code
$(function () {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
});
// modified code
$(function () {
var field = 'IsDlg';
var url = window.location.href;
if (url.indexOf('?' + field + '=') != -1) {
} else {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
}
});
As long as the HTML which embeds the Silverlight control is present, it will show the "Install Silverlight" dialog. If you don't want the dialog to show, you'll have to change the HTML source. You could add JavaScript code to add the HTML dynamically, so that it only shows when necessary. That answer would depend on how you're currently embedding the Silverlight control.
EDIT: You could try code like this:
$(function () {
if (window.location.search.indexOf('IsDlg=1') === -1) {
$.getScript('/_layouts/mediaplayer.js', function () {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
});
}
});
Your code should work, so you probably want to debug for other possible issues.
$(document).ready(function () { // add explicit wait until dom ready
console.log(window.location.search); // just to check that the parameter is present
if(window.location.search.indexOf("IsDlg=1") < 0){ // testing the query string part only
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
}
});
Try that and see how you get on.

Categories