What I am trying to do is rewrite content on the page depending on which object I have selected. I have some objects like so:
function floorPlan(name,rev,sqft,bedrm,bthrm) {
this.name = name;
this.rev = rev;
this.sqft = sqft;
this.bedrm = bedrm;
this.bthrm = bthrm;
}
// 1BR Plans
var a1 = new floorPlan('A1',false,557,1,1);
var a2 = new floorPlan('A2',false,652,1,1);
var a3 = new floorPlan('A3',false,654,1,1);
var a4 = new floorPlan('A4',false,705,1,1);
var a5 = new floorPlan('A5',false,788,1,1);
// The Selected plan
var currentPlan = floorPlan.a1;
I am having the user control this via a .click() function in a menu:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = floorPlan.current;
});
The problem is that currentPlan keeps coming back as undefined and I have no idea why. Should I be defining currentPlan differently? I can't seem to find any resources to help me find the answer.
UPDATED:
I switched out a few parts per your suggestions:
// The Selected plan
var currentPlan = a1;
and....
// Define the currentPlan
var current = $(this).attr('id');
currentPlan = current;
However, everything is still returning undefined in the click function (not initially though).
First of all $('this') should be $(this)
Secondly you're trying to use a read ID from your LI as a variable name. That doesn't work. If you store your plans in an array you can use the ID to search in that array:
var plans=Array();
plans["a1"]=new floorPlan('A1',false,557,1,1);
plans["a2"]=new floorPlan('A2',false,652,1,1);
Then your jQuery code should be altered to this:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = plans[current];
alert(currentPlan);
});
I created a JSFiddle for this. Is this what you were looking for?
Use as floorPlan.currentPlan = a1;
instead of var currentPlan = floorPlan.a1;
Please create a plunker and will correct if any issue.
I spot two errors.
When you write var inside a function, that variable is only accessible with that function. Right now you are creating a new variable in your anonymous function that is "hiding" the global variable with the same name.
So, first remove the var keyword from the assignment in the anonymous function (the one you call on "click").
Secondly I think you mean to assign floorPlan[current].
The final line should read:
currentPlan = floorPlan[current];
Related
I am new to this. I want to insert variable (not text) into my code:
var events = {};
events[new Date("03/05/2019")] = new Event("Math", "green");
Now when you click text "Math" appears.
I want to insert variable - not directly as a text, but like this:
var subject = Math;
var events = {};
events[new Date("03/05/2019")] = new Event( ?subject? , "green");
to get the same result.
First you need to make Math a string, otherwise you are passing the reference Math as a parameter, and Math is an object provided by JavaScript.
You then just need to use the variable that it is assigned to (in this case subject) and pass that as a parameter to the Event class constructor.
var subject = 'Math';
var events = {};
events[new Date("03/05/2019")] = new Event(subject, "green");
I have a problem with define a second class in one Var
Here is the Code: http://jsfiddle.net/2DuQc/
How can I make work this fine?
It's written in JQuery!
var animateEye = $('.rightEye, .leftEye');
doesnt work!
Actually your code won't work because you are overwriting your variabile with only one selector .leftEye so the .rightEye will not have nothing attached to it.
You can use a multiple selector than loop through the result using jQuery each and apply yuor current code.
Use the same class as inner element and find it as a children of the current element.
Code:
$('.rightEye, .leftEye').each(function () {
var animateEye = $(this);
var eyes = animateEye.find(".Eye");
Demo: http://jsfiddle.net/IrvinDominin/rU9E2/
var animateEye = $('.rightEye, .leftEye');
This will give you an array of items, so when you call, say, animateEye.offset(), which one is it supposed to choose? It'll bomb out.
Your current code:
var animateEye = $('.rightEye');
var eyes = $(".Eye");
var animateEye = $('.leftEye');
This will obviously always use .leftEye.
My suggestion? Loop through rightEye and leftEye like so:
var eyes = $('.rightEye, .leftEye');
for(var i = 0; i < eyes.length; i++) {
var animateEye = eyes[i];
}
Well, the problem is quite simple. I got an object of parsed table rows. Code for it is this:
var erg = [];
$("tr").each(function (index) {
var row = {};
var test = $(this).children();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
And I wanna pass a variable var my_variable="blabla" to it without ruining the structure of the object. So how could i bring that object into a structure like this?:
Object{my_variable="my_variable_value"}, Object{my_table=[Object{...}, Object{...}]} //all the objects of the table
$.extend({}, erg, my_variable); only messed my object up.
I want it in that structure so i can pass it as json to my php script and filter my variable easily. Any tips, links, code snippets? :)
I'm not sure at which point you want to add that, but you may simply wrap your array with another object, and add your property to that same object.
This is basically what Florent's answer does, but using an object literal instead of a "class" and prototype:
// (your current code)
var wrapper = {
my_variable: 'something',
my_table: erg
};
You can define a class and add the needed variables to its prototype.
First you need a little utility to do that:
function createSharedStruct() {
// Define a shared structure
var Struct = function() {};
// Define a method to define a shared variable
Struct.share = function(variable, value) {
Struct.prototype[variable] = value;
};
return Struct;
}
And then, update your code:
// Create the shared structure
var rowClass = createSharedStruct();
// Register your shared variables
rowClass.share('my_variable', 'my_variable_value');
var erg = [];
$("tr").each(function (index) {
var test = $(this).children();
// Create a new row
var row = new rowClass();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
// No matter when you share a variable, it will be defined among
// all instances of the same struct.
rowClass.share('my_other_var', 42);
Now you can access shared variables:
console.log(erg[0].my_other_variable); // 42
console.log(erg[1].my_other_variable); // 42
Demo available on JSFiddle.
I'm only working on my 3rd Javascript project, so this is probably easy to answer (at least I hope so).
I have learned to use JS object in place of arrays. In this project I have named multiple object with a nested system of IDs as follows:
animalia = new Object();
animalia.chordata = new Object();
animalia.chordata.actinopterygii = new Object();
animalia.chordata.actinopterygii.acipenseriformes = new Object();
etc.......
I'm having problems calling on objects named this way though. Here is my code:
function expand(event){
var target = event.target;
console.log(target);
var parent = target.parentNode;
console.log(parent);
var parentclass = parent.getAttribute("class");
console.log(parentclass);
if (parentclass == "kingdom"){
var newdiv = document.createElement("div");
var newexpctrl = document.createElement("div");
var parentid = parent.getAttribute("id");
console.log(parentid);
----> var parentobj = window[parentid];
console.log(parentobj);}
else{
var upperclass = searchArray(parentclass);
console.log(upperclass);
var newdiv = document.createElement("div");
var newexpctrl = document.createElement("div");
var parentId = parent.getAttribute("id");
console.log(parentId);
var parentnode_ = document.getElementById(parentId);
console.log(parentnode_);
var gparentId = parentnode_.parentNode.id;
console.log(gparentId);
----> var parentobj = window[gparentId.parentId];
console.log(parentobj);
}
var childnumb = parentobj.children;
}
I am having my problem with the two statements indicated by "---->". In the first case, using a single variable works for pulling up the proper object. However, in the second case, using two variables, I fail to be able to access the proper object. What is the proper syntax for doing this? I have tried a plethora of different syntax combinations, but nothing seems to work correctly. Or should is there a better method for calling on JS objects other than using "window[variable]"?
P.S.- If you haven't figured it out by now, I am working on educational tools for use in learning biology. Thanks once again stackoverflow, you guys rule.
Assuming that the window object has something w/ the property matching a string that's the value of gparentId, you should be able to do:
var parentobj = window[gparentId][parentId];
The problem here is that the square bracket's notation is being applied to too much. gparentId is a string. It doesn't have a property called parentId. You therefore have to do this in two steps. First get:
window[gparentId]
Then get the appropriate property of that object
var parentobj = window[gparentId][parentId];
On a somewhat unrelated note, this isn't very well written JavaScript code:
Creating Objects
When creating new objects, always use the following syntax:
var obj = {};
That's what's generally been accepted as standard, so it's easier for people to read.
Declaring Variables in If Statements
You shouldn't really declare variables inside an if statement, especially when declaring the same variable in the else block, that's really confusing. Instead, declare all the variables at the top in a list and then use them without the var keyword lower down.
var newdiv = document.createElement("div"),
newexpctrl = document.createElement("div"),
parentid = parent.getAttribute("id"),
parentobj;
Note the commas instead of semi-colons which means I don't have to repeat the var keyword. Since the values of newdiv, newexpctrl and parentid are the same in either case, I give them their values straight away, making the contents of the if statement much shorter and easier to digest.
Result
function expand(event){
var target = event.target;
var parent = target.parentNode;
var parentclass = parent.getAttribute("class");
var newdiv = document.createElement("div"),
newexpctrl = document.createElement("div"),
parentid = parent.getAttribute("id"),
parentobj, upperclass;
if (parentclass == "kingdom"){
parentobj = window[parentid];
}else{
upperclass = searchArray(parentclass);
var _parentId = document.getElementById(parentId).parentNode.id;
parentobj = window[_parentId][parentId];
}
var childnumb = parentobj.children;
}
Note that I've left var _parentId inside the if since I think it probably improves readability, but you may choose to take it outside the if, since it will pollute the namespace of the function anyway.
I am working on a project in Google Blogger. First i want to explain a thing.
In blogger every post that is created has a unique id assigned to it by blogger itself. This id can be retrieved using Blogger JSON. So i have retrieved the ids of four recent posts using JSON.
I want to wrap these first four id containers around a DIV container using JQuery or Javascript.
The problem is when i use these ids absolutely in the selector $ and use the wrapAll() function the id container's gets wrapped up. But as i said i'm using JSON to get the container id's so the values of ID's are stored in variable's and when i use those variable as selection for wrapAll() function it doesn't work.
I have demos of both those situation's which can be seen by going to this blog http://youblog-demo.blogspot.com/ and using the firebug console to run these code.
Situation 1 when i use absolute container ids
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
$("#3337831342896423186,#123892177945256656,#9095347670334802803,#2525451832509945787").wrapAll('<div>');
}
};
Situation 2 when i use variable's to select the containers
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
var front_name = "#";
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
}
};
So when i use the situation 2 code then it doesn't work but the situation1 code works fine. Can anybody help me with this
You need to pass in the selector as a string, not a list of arguments;
$(joined_id_0+', '+joined_id_1+', '+joined_id_2+', '+joined_id_3).wrapAll('<div>');
Or even better, replace all of:
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
With:
$('#'+id_coll.join(', #')).wrapAll('<div>');
And remove the line: var front_name = '#';
You have to concatenat the ids, separated by a comma, as in #id1, #id2, ....
You can do that this way:
[joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')
The whole line:
$([joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')).wrapAll('<div>');
If it doesn't works, check the what is returned by [joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',') (alert() it, or use console.log).