How to pass an array variable into a new window through javascript - javascript

I am launching an html page when users click a button. I need to be able to pass in an array of addresses to the new window so that I can load them into a table, however I have been unable to find any way to pass an array over to the new window.
My most recent attempt looks like the following:
<button onclick="openWindow(['Joe Smith\n1 Address\nCity 12345',
'Joe Smith\n2 Address\nCity 12345'])">Button</button>
function openWindow(addresses){
var myWindow = window.open("NewPage.html");
myWindow.addresses = addresses;
}
And then in NewPage.html I've got:
<script type="text/javascript">
function bodyLoaded() { //gets called when the body loads
var addresses;
alert(addresses);
}
</script>
I always get undefined in the alert on the new window. I did confirm that I am getting the addresses if I set up an alert in the openWindow() function.
I've tried several other things as well, including using localStorage (How to pass an array to a new page using javascript?) altho I don't know if I did it correctly. I also tried executing the function to load the table on the new window from the openWindow function (passing in the addresses variable) but I keep getting errors saying "Error: Object doesn't support property or method". For example:
function openWindow(addresses){
var myWindow = window.open("NewPage.html");
myWindow.loadTable(addresses); //the loadTable function exists in a .js file
}
Ideally I just want to pass a single array to the new window but I've been stuck on this for a while now. Any assistance or suggestions would be greatly appreciated.

One possibility is to pass the array of params as a query in the url. So something like this:
var myWindow = window.open("NewPage.html?addresses[0]=Joe Smith\n1 Address\nCity 12345&addresses[1]=Joe Smith\n2 Address\nCity 12345");
Then in javascript using this function
<script type="text/javascript">
function bodyLoaded() { //gets called when the body loads
var urlParams = new URLSearchParams(window.location.search);
var addresses = urlParams.get('addresses'));
alert(addresses);
}
</script>
Edit:
Also localstorage works according to this answer: (How to pass an array to a new page using javascript?)
window.localStorage.setItem("cart", JSON.stringify(cart)); // Saving
var cart = JSON.parse(window.localStorage.getItem("cart")); // Retrieving

The new window is open by code so the code has some control over that window. Try something like this.
function openWindow(addresses) {
var myWindow = window.open("newpage.html");
myWindow.onload = function() {
var myDiv = this.document.createElement('div');
this.document.body.appendChild(myDiv);
for (var i = 0, a; a = addresses[i]; ++i) {
myDiv.innerHTML += a;
}
}
}

Related

Using Javascript code twice

First of all I want to say that I am sorry for not using the Code sample. This is my first time asking on stackoverflow and I found it really confusing.
I have this javascript code which works perfectly, but when I try to duplicate it and change the variable names it doesn't seem to work.
JavaScript
function saveEdits() {
var editElem = document.getElementById("edit");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML=localStorage.userEdits;
}
the way i tried to edit(im new to javascript i have no idea what i was doing):
JavaScript
<script type="text/javascript">
function saveEditsplus() {
var editElemplus = document.getElementById("editplus");
var userVersionplus = editElemplus.innerHTML;
localStorageplus.userEditsplus = userVersionhtml;
}
function checkEditsplus() {
if(localStorage.userEditsplus!=null)
document.getElementById("editplus").innerHTML=localStorageplus.userEditplus;
}
</script>
in your code, you changed the name of localStorage to localStoragePlus - but localStorage is something provided by your browser (see .
If you change it back to localStorage, it might work again.
For reference, here's the part with the renamed variable:
function saveEditsplus() {
var editElemplus = document.getElementById("editplus");
var userVersionplus = editElemplus.innerHTML;
localStorageplus.userEditsplus = userVersionhtml;
^^^^
}
By the way, you're not using localStorage correctly. If you want to save something across page reloads, you need to call "set" I learned that this is not true. sorry for the confusion. (tutorial)
Yes, looks like you have no idea what the code is doing… localStorage is a browser api, you can't just rename it (like you can't - and didn't - change document or innerHTML).
However, there's no reason to rename any of the variables at all. By using the var declarations, you made them local to each of the functions, so they won't interfere with each other anyway. All you need to change are the references to the element:
function saveEditsplus() {
var editElem = document.getElementById("editplus");
var userVersion = editElem.innerHTML;
localStorage.userEditsplus = userVersion; // no …html suffix, either
// ^^^^^^^^^^^^^ the storage reference is global, though
}
function checkEditsplus() {
if(localStorage.userEditsplus!=null)
document.getElementById("editplus").innerHTML=localStorage.userEditplus;
}
However, even better than copying the code would have been to give these functions parameters - one for the id of the element, one for the property of localStorage that is supposed to be used.
You cannot modify the localStorage (browser api)!
function saveEdits() {
var editElem = document.getElementById("edit");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}

Trouble with my javascript function, I think with document.getElementById('vodObj').innerHTML

I am trying to write a JavaScript function that will update the labels and attributes of my CSS menu. The CSS menu I create dynamically with PHP and a database, and I want to update the CSS menu so the top item is the currently selected one, and the currently selected one does not appear in the list below it. Now that you know what I am trying to accomplish, here is my code:
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function switchVod(vodID) {
alert("switchVod ran");
var x = document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i = 0; i < vodName.length; i++) {
if (i != vodID) {
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function () {
switchVod(id);
}
}
}
alert("after for loop");
alert("1"); //works
document.getElementById('vodObj').innerHTML = 'some string';
alert("2"); //doesn't work
document.getElementById("vodDate").innerHTML = " some string ";
alert("finished"); //doesn't work
}
Deeper in the webpage, after getting my information from the database and storing the strings I need in the vodName, vodAddress, and vodDate arrays, and creating the CSS menu and <div id="vodObj"> and <div id="vodDate">, I initialize the page by calling
window.onload = switchVod(0);
It wasn't doing what I hoped, so I added some alert() calls to see how far into the function it was going before failing. alert("after for loop") worked, as did alert("1"). But, alert("2") does not pop up, and neither does alert("finished"), so I think the problem is with document.getElementById('vodObj').innerHTML = 'some string';.
Any ideas of what I could be doing wrong?
window.onload = switchVod(0);
executes switchVod and assigns the return value to window.onload. So it is very likely that the elements you are trying to access (#vodObj in particular) are not loaded yet.
You have to assign a function to window.onload:
window.onload = function() {
switchVod(0);
};
See also Why does jQuery or a DOM method such as getElementById not find the element?
There is an other problem which will encounter eventually:
x.onclick = function () {
switchVod(id);
}
You never defined id anywhere, and if you define it inside the loop, you will run into closure issues. See JavaScript closure inside loops – simple practical example for a solution.
y[0].innerHTML = vodName[vodID];
At this point vodName is an empty array. Actually throughout all of this, you never provide any values to vodName. Please provide complete document.

Titanium JavaScript: How to pass data/values from one window to another window

In objective c we can pass data between two classes very easily by nextClassname.recievedVariable = passedVariable;
i tried same with titanium, but failed
I tried as follows
in Second Class
$.table.addEventListener('click', function(e) {
var selected = e.row;
alert(e.row.title);
var TodayStatus = Titanium.UI.createWindow({ url:'TodayStatus.js' });
TodayStatus.seletedProj = e.row.title;
// var TodayStatus = new Alloy.createController("TodayStatus");
TodayStatus.getView().open();
});
in the first Calss whic we have to recieve string from another class
var win = Ti.UI.currentWindow;
Ti.API.info(win.seletedProj);
But causes errors like
message = "'undefined' is not an object (evaluating 'win.seletedProj')";
[ERROR] : name = TypeError;
You can pass the data by passing parameter like this.
x.addEVentListener('click', function(e){
var controller = require('controllerPath').createWindow(e.value);
controller.open();
})
And in controller.js
exports.createWindow = function(value)
{
//whatever You like to do with UI
}
If you create a new window by using the 'url' parameter it automatically puts that code into it's own Sub-context and it isn't possible to pass complex objects accross, see here:
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.UI.Window
I don't tend to do it this way anymore.
The way i would do it would be to create your todayStatus window as a common js class:
// todayStatus.js
var win = Ti.UI.createWindow({ top:0, left: 0, right: 0, bottom:0, etc... });
//any extra visual building code can go here
win.open();
exports.seletedProj = function(rowTtl){
//this function is available outside the class
}
Then you can reference it from your main class like this:
// main.js
var TodayStatus = require('todayStatus');
TodayStatus.seletedProj(e.row.title);
etc...
Hope that helps
see link here for how to do it in Alloy,
https://github.com/aaronksaunders/alloy_fugitive/blob/master/app/controllers/Fugitives.js#L29
but basic idea is to pass the object as a parameter when creating the new controller.
$.table.addEventListener('click', function(_e) {
var detailController = Alloy.createController('FugitiveDetail', {
parentTab : $.fugitiveTab,
data : fugitiveCollection.get(_e.rowData.model)
});
$.fugitiveTab.open(detailController.getView());
});
The link I provided has a complete solution using Alloy

Can i get any unique identity for new opened window in javascript?

I want to keep separate values for each window and the values should be kept same for the that window although i reload that window.
window.open will return a windowObjectReference which you can for use all window operations.
So if you want to open and reload a window you can do it like this:
var myWindow = window.open("http://whatever");
myWindow.location.reload(true);
You might also want to read the documentation on window.location.
Try this:
var winArr = { keys:[] , values:[] };
var newWindowForOpen= 'http://stackoverflow.com/questions/12226191/can-i-get-any-unique-identity-for-new-opened-window-in-javascript';
var winExist=false;
for(var i = 0; i < winArr.keys.length; i++){
if(winArr.keys[i] === newWindowForOpen){
winExist = true;
}
}
if(!winExist){
winArr.keys.push(newWindowForOpen);
var obj={}; // contais information about an open window, your window information
winArr.values.push(obj);
}
I hope it works for you.

Object has no method Javascript

I don't know why I am getting this problem. I have used prototype before in javascript and it works fine but for some reason it is not working here:
test.html:
<script type="text/javascript">
$(document).ready(function(){
UserOptions("test");
});
</script>
UserOptions.js:
function UserOptions(username){
...
var userOptions = document.createElement("div");
userOptions.className = "userOptions";
**this.createBtns(userOptions);**
userContainer.appendChild(userOptions);
contentCenter.appendChild(userContainer);
contentCenter.appendChild(br);
BuddyList();
}
UserOptions.prototype = {
createBtns:function(parent){
var self = this;
/* Add Buddy Button */
var addBtnContainer = document.createElement("div");
addBtnContinaer.className = "addBtnContainer";
...}
I keep getting the error Object has no method 'createBtns'
You forgot the new keyword. Now it's trying to call your constructor as a regular function, and this will point to window or whatever.
new UserOptions("Fred");

Categories