JavaScript - Create An Object On The Fly
I have a select with a OnChange Function. I would like to know how to create a different object depending on the selection on the Select.
Example: MySelect have Option 1 and Option 2, so If (Myselect.value == Option 1) {Create Object 1} If (Myselect.value == Option 2) {Create Object 2} I'm using the object under <body> and it's working, but when I'm trying to use it under a <script> does not work. This is the object I'm trying to create: (It is a map) so what I'm trying is to change the values or map depending on the selection of the Select. <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="900" height="600" id="zoom_map" align="top"> <param name="movie" value="us_albers.swf?data_file=senate.xml" /> <param name="quality" value="high" /> <param name="bgcolor" value="#FFFFFF" /> <embed src="us_albers.swf?data_file=senate.xml" quality="high" bgcolor="#FFFFFF" width="100" height="100" name="Clickable U.S. Map" align="top" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> </embed> </object> Thank you very much Similar TutorialsHi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I'm writing a script in javascript(actually a chrome extension) and I need an object that I can write to it like this(sorry, don't know how to explain it better) and then I convert it to string with format of json. Code: id[129].weekDay[6].hour[23] = 0 Here, id is an array, that each element in it contain another array(weeksDay) and in that array each contain another array(hour). The id indices are unlimited, for weekDay 7 and hour 24. I searched in google but i couldn't find what I wanted. Actually don't know the best keyword to search.(objects in arrays?) I don't know what exactly it is called, I can write it's declaration in VB.NET if that helps you. I know I can use the functions like parseFromString() to access and modify an existing XML documents, but is it possible to use JavaScript to create a blank xml document? I want to take data entered into the client, package it up as XML and use ajax to transmit it to the server. So far I've written my own class to create a simple xml document, but I'd like to do it properly with the inbuilt functions. This is in reference to Crockford's articles found he http://javascript.crockford.com/prototypal.html http://javascript.crockford.com/private.html I'm attempting to understand the use of privileged methods when used with Object.create. I put together a quick demo (code below) that shows what happens when I use Object.create to create a new object based on one that has a privileged method. The outcome is not pleasant, as changing the value in the first object also changes it in the second. Unless I am reading Crockford's articles incorrectly, this makes Object.create almost useless for anything but objects that have only public members. I've seen many JavaScript programmers use closures extensively to create private members, and that still holds to be a good programming practice. However I still can't find an elegant way to create inheritance in combination with closures in JavaScript, given downfalls such as the one I mentioned above. With all of that said I still think Crockford has a nice way of programming, creating factory functions that produce objects, staying away from the prototype property and making the language look more functional. Here's the code to demonstrate what I'm referring to. Firebug needs to be enabled to view the console.debug output, otherwise convert them to alerts. Code: if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } var o = (function() { var msg = "hi"; return { msg: function(m) { if (m === undefined) { return msg; } msg = m; } }; })(); var foo = Object.create(o); var bar = Object.create(foo); console.debug(foo.msg()); // "hi" foo.msg("what?"); console.debug(foo.msg()); // "what?" console.debug(bar.msg()); // "what?" I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Ignore post (if mod, please delete)
Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. I am trying to troubleshoot my javascript function below. Code: <script type="text/javascript"> function txtboxfill(fillobj) { var rChar=String.fromCharCode(13); var myVal = "To: " + this.form.to.value + rChar; myVal = myVal + "From: " + this.form.from.value + rChar; myVal = myVal + "Subj: " + this.form.subj.value + rChar + rChar; myVal = myVal + "Message: "; fillobj.value = myVal; } </script> Then I have a text box input field with an Code: <input type="text" id="tp" name="to" size="34" class="totext" onkeyup="txtboxfill(this.form.msg_area);"> and when I enter text in this field it gives me a 'this.form.to' is null or not an object and does not populate the textarea. BTW, msg_area is the id of my textarea. Thank you. Hello, below you will find two objects, background and photo1, which I need help cleaning up a bit. This will eventually be imported using Json but for now during development it sits as is in my script. I need help with a couple things: - You will notice the 'val' property is identical in both objects. How can I move this into an outside function that each object can share? I'm having trouble bc I couldn't get 'this' to work outside of its current context. - Second, how can I restructure this so that I can instantiate a new object. So if I wanted to add a new layer I'd like to do something like importLayers.push[new Layer('photo2')] Code: var importLayers = { background: { layerType: 'background', index: 0, layerContent: { content: function() { return $(element).find('#background_Content'); }, width: 850, height: 530, xPos: 0, yPos: -150, skewX: 0, skewY: 0, angle: 0, originX: function() { return (this.sWidth() / 2); }, originY: function() { return (this.sHeight() / 2); }, scaleX: 1, scaleY: 1, sWidth: function() { return this.width * this.scaleX; }, sHeight: function() { return this.height * this.scaleY; }, aspect: 0, opacity: 100, val: function(prop, val) { switch(prop) { case 'width': if(plugin.constrain) this.scaleX = this.scaleY = val / this.width; else this.scaleX = val / this.width; break; case 'height': if(plugin.constrain) this.scaleY = this.scaleX = val / this.height; else this.scaleY = val / this.height; break; case 'angle': this.angle = val; } buildTransformation(this, this.content()); } }, }, photo1: { layerType: 'photo', index: 1, layerContent: { content: function() { return $(element).find('#photo1_Content'); }, width: 1920, height: 1280, xPos: 0, yPos: 0, skewX: 0, skewY: 0, angle: 0, originX: function() { return (this.sWidth() / 2); }, originY: function() { return (this.sHeight() / 2); }, scaleX: .15625, scaleY: .15625, sWidth: function() { return this.width * this.scaleX; }, sHeight: function() { return this.height * this.scaleY; }, aspect: 0, opacity: 100, val: function(prop, val) { switch(prop) { case 'width': if(plugin.constrain) this.scaleX = this.scaleY = val / this.width; else this.scaleX = val / this.width; break; case 'height': if(plugin.constrain) this.scaleY = this.scaleX = val / this.height; else this.scaleY = val / this.height; break; case 'angle': this.angle = val; } buildTransformation(this, this.content()); } }, } } Greetings, I have a floating object that work find within my page. However, I would like to only show after a button is clicked. Any ideas how to do this. Thanks Hi All, (Another Post LOL) Ive been getting alot of help with js recently THANKS! One last thing and i shouldnt be on here for a while How would i go about doing this Code: <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="750" height="550" codebase="http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0"> <param name="movie" value="SWF/helicopter.swf"> <param name="quality" value="high"> <param name="menu" value="false"> </object> into JS using .innerHTML = "Above Stuff"; I always get an error + i dont know how im going wrong with the quotes :S ANY HELP (GOOD STUFF); Thanks In Advance, Jamie. NOM NOM NOM! Code: function globals() { this.states = ""; } now I can: Code: globals.states = .... how to extend first code to be able: Code: globals.states.something = .... ? How can i display a javascript object having [CODE]var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}].[CODE] in a table in jsp page? Regards, Anas I am doing my homework for my class, and I don't usually ask for this much help because I get most of them done by myself. However, I am having a really hard time to understand this time. I have lots lots of questions...I tried to follow the instructions that I got from my professor, but it seems not clear enough to me... If anyone can fix or add on my codes, I will be really really appreciated....and here is the instructions and my codes.. If the form validates, instead of returning true, call the GetValues() function followed by the DisplayOutput() function. so, I changed result true to calling functions like this, Code: if (blnError == true){ return false; } else { DisplayOutput(); GetValues(); } In the .js file, create a PortraitOrder class using the following specifications Properties: portrait, copies, size, buyer Method: CalculateCost () -- determines the size (radio buttons) and then mutiplies the related cost by the number of copies Code: function PortraitOrder(){ var cost; this.copies = ""; this.portrait = ""; this.size = ""; this.buyer = ""; var CalculateCost = { met1 : function () { if(size == 0){ cost = this.copies * 10 } else if(size ==1){ cost = this.copies * 20 } else if(size ==2){ cost = this.copies * 10 } else if(size ==3){ cost = this.copies * 30 } else{ cost = this.copies * 20 } } } } Create a new instance of the class named portraits as a global variable in the ,js file -" I don't see why I need this. So I did not create Create a GetValues() function that will retrieve the values from the form fields (document.forms[0].element.value) and assign them the properties of the instance of the PortraitOrder class. use a for loop to retrieve the value from the radio buttons use the prototype property to add a new property named email to the instance of the class retrieve the value from the form field and assign it to the new email property Code: function GetValue(){ this.copies = document.forms[0].Copies.value; this.buyer = document.forms[0].Buyer.value; var file = document.getElementsByName('Filename'); for(var i = 0; i < file.length; i++){ if(file[i].checked){ this.portrait = file[i].value; } } var sizes = document.getElementsByName('Size'); for(var i = 0; i < sizes.length; i++){ if(sizes[i].checked){ this.size = sizes[i].value; } } GetValue.prototype.email = document.forms[0].Email.value; } Create a DisplayOutput() function that calls the CalculateCost () method for the current instance of the class. displays the image using the value from the portrait property which contains the filename. Be sure to include height and width (and that would be why all of the images had to be the same dimension. These values can be hardcoded. The filename, however, may NOT be hard coded.. it must use the object.property format. displays the buyer, email, copies, size, and cost using the object.property format (document.forms[0].element.value is not permitted) The cost must be formatted as ##.## where # represents a number (Hint: Use a method of the Number class). It is NOT okay just to concatenate .00 to then end of the cost. Code: function DisplayOutput(){ CalculateCost.met1(); document.write("buyer: " + this.buyer); document.write("Email: " + email); document.write("Portrait: " + this.portrait); document.write("Copies: " + this.copies); document.write("Cost: " + "$"+cost.toFixed(2)); document.write("Thank you"); } The order form must include the site's header and footer and coordinate with the rest of the site. There is no form processing file, everything is done in the .js file. You may think like, this is horrible codes. And yes, it is. I know probably this is totally odd. This is why I came here for ask help. Also, I spent days to tried, but I could not get any idea...Anyone please help me on this? I am rather new to javascript programming and not sure if this is the best approach to handle a problem. In setting up a simple image display that can later be modified to a rotator, I am using the following code window.document.display1.src = image1.src; now the question is when modifying that to be more dynamic, where display1,display2,.. can refer to a different image (or set). var Image = "image"; var Display = "display"; for (i=1; i<n; i++){ window.document.this[Display+i].src = this[Image+i].src; } I know the right hand side of the equation is working (alert() displays the right soure), but the problem is the left hand side. I guess because of me not fully understanding the way objects work. why this[] works on the right and not on the left? and how do I resolve it? All your comments, and a push in right direction are appreciated. |