JavaScript - Literal Notation: Creating New Objects
Hello,
I have the following code: A = { "value" : "a", }; B = A ; B.value = "b"; alert (A.value); // => b I expected A.value to be "a". Can someone explain what I'm thinking wrong? And: how can I change values of a new object, without changing the parent-object ? tnx Similar Tutorialsok, so I can make an object, I can also make a new instance of that object and have it running around the screen at the same time. What I'm a bit confused about is how to go about things when I want X number of these objects. So instead of making objects seperately I need a loop. Instead of referring to each object seperately every time I want to redraw it, I want to loop through all instances of the object. Except I can't quite see how one goes about doing this. I need something like (pseudocode) Code: for (i = 0;i <= 10; i++) { var dot + i = new Dot; } and var b = numberOfDots; for (i = 0;i <= b; i++) { dot + i +.moveMe(); drawDot(dot + i + .posY, dot + i +.posX); } obviously this code does not work but it represents the essence of what i'm trying to do and can't get my head around, no matter the google searches I try. I'm trying to get a return of Code: [ ["red","green","blue"] ,["blue","red","green"] ] from a text file that contains Code: red,green,blue blue,red,green Using the following function Quote: Originally Posted by Old Pedant Code: function WRITE_FILE_AS_JSON(file) { fso = Server.CreateObject("Scripting.FileSystemObject"); myPath=Server.MapPath("timecards/" + file); if(!fso.FileExists(myPath))return; myfile = fso.OpenTextFile( myPath, read); var lines = myfile.readAll().split("\n"); Response.Write("[\n"); for ( var i = 0; i < lines.length; ++i ) { Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); } Response.Write("]\n"); myfile.Close(); Response.End(); } The darn thing keeps returning Quote: 500 (Internal Server) Error as a result of the line Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); And I don't know how to fix that line... Though I know nothing about Javascript, that didn't stop them from assigning me the task of mothballing our Excel spreadsheets and going to fillable .PDF forms. Here's my first of many questions: In one of my fillable PDF forms, I take the numbers (entered by the user) from two or three fields and calculate those placing the answer in a seperate field. Since we work with very large, and very small numbers, I want the number in the answer field to be displayed in scientific notation. Adobe Acrobat is not very flexible when it comes to selecting a number format, so a script is obviously needed to do the conversion. I've also noticed that Adobe doesn't like the user entering a number in a field in scientific notation. My number calculates out correctly if you enter .000000274 in the field, but does nothing if you enter 2.74E-7. Help with that would also be greatly appreciated. Don I keep getting this error and I'm not sure why var flashvars = {'regkey':"<?php $_GET[regkey]?>",'pkey':"<?php $_GET[pkey]?>"}; unterminated string literal [IMG]chrome://firebug/content/blank.gif[/IMG]var flashvars = {'regkey':"<br />\n I have the following code which attaches a function to events in x number of comboboxes (x will probably always = 4, but I do not want to hard-code this). I wish to pass the value of i to the function being attached as well as the value of tempData. In other words, I want the parameters in function to be the value, not a reference variable. In the current example, I am using the hard-coded variable ci. This I want to be replaced by a literal created when the event handler is attached (the value of the loop variable i). Also, notice that I get the filter value in the event handler (assigned to the variable ct). I would like to replace this code with the value of tempData which would also be determined when the evenet is attached (it is the same value in this case, but it keeps the onChange event from having to do this each time it runs). Code: var props = { col_0: "select", col_1: "select", col_2: "select", col_3: "select", btn_reset:true, display_all_text: "-Show All-", on_filters_loaded: function(o){ //reset all filters var slcIndexes = o.GetFiltersByType(o.fltTypeSlc, true); //o.fltTypeSlc = 'select' for(var i=0; i<slcIndexes.length; i++){ //this public method returns a filter DOM element by column index var slcElm = o.GetFilterElement(slcIndexes[i]); //tempData = slcElm.options[slcElm.selectedIndex].text; //window.alert(tempData + " " + slcElm); tf_AddEvent(slcElm, 'change', onchangeFn=function(){ //ci is the column index for the column to filter on. ct is the new text from the combobox to filter on var ci; ci = 2; var ct = tf_outputTable.GetFilterValue(ci); tf_outputTable.ClearFilters(); //window.alert("ci= " + ci + " ct= " + ct); tf_outputTable.SetFilterValue(ci, ct); tf_outputTable.Filter(); }); //end tf_AddEvent } } } setFilterGrid("outputTable",props); I need to find a way to check if a field contains sql commands. To begin with, lets just say as an example:select, delete, drop, truncate <script type="text/javascript"> function validate () { var literals= /select/; user_input = document.forms[0].input1.value.search(literals); if (user_input == -1) { alert("test123"); } } </script> <body> <form > <input type="text" size="25" name="input1" value=" "> <input type="button" onClick="validate()" value="check" /> </form> I am new to JS and regular experssions. How do I make it in my regular expression so not only am I searching for /select/ but also for the other sql commands (or anythign for that matter)... essentially multiple literals... eg if it contains /select OR delete OR truncate/ etc. sorry if this is confusing. let me know if i can help in any other way. thanks guys! Hello, I created a simple WYSIWYG for creating CSS based webpages. It works exactly as assumed in Safari and Chrome. However, in firefox, when you copy/paste more than one line of text, instead of formatting it as html, in puts in line breaks causing the array storing all of the data to break into multiple lines and causing an unterminated string literal. Can anyone, 1. suggest why it is behaving this way? 2. suggest a work around to allow it to work on FF? Hi guys , i am getting this error " unterminated string literal" but iam unable to locate the problem..iam using fire bug for firefox.. any idea from where this error comes ? thanks So I can't figure out why I keep getting the error.... Code: unterminated string literal document.write("<input type=\"button\ value=\"" + phrases [i][j] + "\" Code: <form name="pirateForm"> <div align="center"> <script type="text/javascript"> phrases = [["Greetings","hello","pardon me","excuse me","hows it going"], ["People","sir","madam","woman","children"], ["Questions","where is","can you help me find","is that","how far is it to?"], ["Ariticles","the","my","your","there"], ["Adjectives","outstanding","attractive","happy","dead"], ["places","restroom","restaurant","hotel","pub"], ["Desires","I would like to","I desire","I wish I knew how to","my mother told me to"], ["Actions","have a great dinner","have a cocktail","fall on the ground","get drunk"]]; for(var i = 0; i < phrases.length; i++) { var category = phrases[i][0]; document.write("<tr valign='top'><td>" + category + ": <td>"); for(var j = 1; j < phrases [i].length; j+=2) { document.write("<input type=\"button\ value=\"" + phrases [i][j] + "\" onClick='document.pirateForm.Output.value += \"" + phrases [i][j+1] + "\";'>\n"); } } </script> </div> <div align="center"> <textarea id="task_list" rows="5" cols="130"></textarea> <input type="button" value="Clear" onClick="this.form.reset()" /> </div> </div> </form> im sure its the scripting, im new to js, can anyone Tell me why im getting these 2 error messages? thank you!!!!!!! detailed error: unterminated string literal Error: onPageUnload is not defined function writeMovie1() {detectBrowser();if(windowsInternetExplorer) {document.write('<object id="id3" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="150" height="16" style="height: 0px; left: 160px; position: absolute; top: 150px; width: 150px; z-index: 1; "><param name="src" value="musicfiles/VenusStereo.m4a" /><param name="controller" value="false" /><param name="autoplay" value="true" /><param name="scale" value="tofit" /><param name="volume" value="100" /><param name="loop" value="true" /></object>');} else if(isiPhone) {document.write('<object id="id3" type="video/quicktime" width="150" height="16" style="height: 0px; left: 160px; position: absolute; top: 150px; width: 150px; z-index: 1; "><param name="src" value="musicfiles/VenusStereo.m4a"/><param name="controller" value="false"/><param name="scale" value="tofit"/></object>');} else {document.write('<object id="id3" type="video/quicktime" width="150" height="16" data="musicfiles/VenusStereo.m4a" style="height: 0px; left: 160px; position: absolute; top: 150px; width: 150px; z-index: 1; "><param name="src" value="musicfiles/VenusStereo.m4a"/><param name="controller" value="false"/><param name="autoplay" value="true"/><param name="scale" value="tofit"/><param name="volume" value="100"/><param name="loop" value="true"/></object>');} setTransparentGifURL('Media/transparent.gif');function applyEffects() {var registry=IWCreateEffectRegistry();registry.registerEffects({stroke_0:new IWStrokeParts([{rect:new IWRect(-5,5,10,467),url:'Welcome_files/stroke.png'},{rect:new IWRect(-5,-5,10,10),url:'Welcome_files/stroke_1.png'},{rect:new IWRect(5,-5,705,10),url:'Welcome_files/stroke_2.png'},{rect:new IWRect(710,-5,11,10),url:'Welcome_files/stroke_3.png'},{rect:new IWRect(710,5,11,467),url:'Welcome_files/stroke_4.png'},{rect:new IWRect(710,472,11,10),url:'Welcome_files/stroke_5.png'},{rect:new IWRect(5,472,705,10),url:'Welcome_files/stroke_6.png'},{rect:new IWRect(-5,472,10,10),url:'Welcome_files/stroke_7.png'}],new IWSize(716,477))});registry.applyEffects();} function hostedOnDM() {return true;} function onPageLoad() {loadMozillaCSS('Welcome_files/WelcomeMoz.css') adjustLineHeightIfTooBig('id1');adjustFontSizeIfTooBig('id1');adjustLineHeightIfTooBig('id2');adjust FontSizeIfTooBig('id2');Widget.onload();fixupAllIEPNGBGs();fixAllIEPNGs('Media/transparent.gif');applyEffects()} function onPageUnload() {Widget.onunload();} ok so Code: <p> Howdy <p> expressed as a literal string that is passed to the setTimeout() function might look like this: Code: setTimeout("document.getElementById('first').innerHTML = '<p>' + 'HOWDY' + '<\/p>';", 2000); ..so I guess you can't just put quotes around an expression like this: "'<p> HOWDY <\/p>;" So tags have to be isolated, but it get confusing with expressions like this, which I am not sure how to express as a string: Code: <p><h2 class="pos_left"> <img src="car1.jpg" name="slide" width="400" height="250" /> </h2> </p> ^ I wish I could change the " in there to ' and then just wrap the whole thing in double " This is what I came up with but it did not work: Code: setTimeout("document.getElementById('first').innerHTML = '<p>' + '<h2' + 'class='pos_left'' + '>' + '<img' + 'src='car1.jpg'' + 'name='slide'' + 'width='400'' + 'height='250'' + '/>' + '</h2>' + '<\/p>';", 4000); Hi.. I am facing identifier starts immediately after numeric literal error in firefox onclick="document.location.href='<%= themeDisplay.getPathMain() %>/portal/ext/asite/assignOrg'"/> can any 1 solve this?? function($) { $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, } So I see the '.superfish' method being added to the object '$.fn'. I find it interesting that the first order of business is to declare 'sf' and stuff in to it some value '$.fn.superfish' which I do not fully understand. Also the statement c=sf.c How can 'c' be set to equal 'sf.c' when no 'sf.c' has been declared yet? Thanks! Good day, I have the following code: Code: var img = new Image(); img.myProperty = 'something'; I've tried Image.prototype.myProperty and a few other things. It seems IE just doesn't want me extending the Image object. Is there a known work-around? Thanks I am able to do the following; Code: alert(myObject.Income.EESA.Name); However I'm looking at Code: alert(myObject.Income[0].Name); Or even better, not the full name, just "EESA". I need to loop through as you can see at the end of this script what I'm working on. Code: <script type="text/javascript"> var EESARate = 289.3; var DLARate = 111.20; var CARate = 61.35; var SkyCost = 54.75; var PerfectHomeCost = 28.17; var CreditExpertCost = 14.99; var UnitedUtilitiesCost = 8.13; var BTCost = 57.18; var AdobeCCCost = 46.88; var TVLicenceCost = 6.06; var GasCost = 10.00; var ElectricCost = 20.0; var ServerPackageCost = 9.99; var USDValue = 123; //Fetch the value var myObject = { "Income": { "EESA": { "Name": "Enhanced Employment and Support Allowance", "Amount": { "GBP": EESARate, "USD": EESARate * USDValue }, "Frequency": { "When": "14", "Next": "30/10/2014" }, "Description": "", }, "DLA": { "Name": "Disibility Living Allowance", "Amount": { "GBP": DLARate, "USD": DLARate * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "CA": { "Name": "Carers Allowance", "Amount": { "GBP": CARate, "USD": CARate * USDValue }, "Frequency": { "When": "7", "Next": "Saturday" }, "Description": "", }, }, "Bills": { "Sky": { "Name": "Sky", "Amount": { "GBP": SkyCost, "USD": SkyCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "PerfectHome": { "Name": "Sky", "Amount": { "GBP": PerfectHomeCost, "USD": PerfectHomeCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "CreditExpert": { "Name": "Experian Credit Expert", "Amount": { "GBP": CreditExpertCost, "USD": CreditExpertCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "UnitedUtilities": { "Name": "United utilities", "Amount": { "GBP": UnitedUtilitiesCost, "USD": UnitedUtilitiesCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "BT": { "Name": "British Telecomunications", "Amount": { "GBP": BTCost, "USD": BTCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "AdobeCC": { "Name": "Adobe Creative Cloud Suite", "Amount": { "GBP": AdobeCCCost, "USD": AdobeCCCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "TVLicence": { "Name": "Television Licence", "Amount": { "GBP": TVLicenceCost, "USD": TVLicenceCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, "Gas": { "Name": "Eon Gas", "Amount": { "GBP": GasCost, "USD": GasCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "Electric": { "Name": "Eon Electric", "Amount": { "GBP": ElectricCost, "USD": ElectricCost * USDValue }, "Frequency": { "When": "7", "Next": "Wednesday" }, "Description": "", }, "ServerPackage": { "Name": "1&1 Unlimited Plus (12 mo. term)", "Amount": { "GBP": ServerPackageCost, "USD": ServerPackageCost * USDValue }, "Frequency": { "When": "30", "Next": "XX/XX/XX" }, "Description": "", }, }, }; var IncomeTotal = 0; for (var k in myObject.Income) { if (myObject.Income.hasOwnProperty(k)) { ++IncomeTotal; } } alert(myObject.Income.EESA.Name); document.write('<table>') for(i = 0; i < IncomeTotal; i++){ document.write('<tr>') document.write('<td>row ' + (i+1) + ', column 0</td>') document.write('</tr>') } document.write('</table>') var TotalBills = 0; for (var k in myObject.Bills) { if (myObject.Bills.hasOwnProperty(k)) { ++TotalBills; } } //alert(TotalBills); </script> I'm having a spot of trouble in making my functions work and my book seems to be pure rubbish. I'm sure that the error is purely syntax, although it may be something more. Code: <script type="text/javascript" src="flowers.js"></script> <script type="text/javascript"> function pageSetup() { var today = new Date(); // this creates a date object with today's date var banner = displayBanner(today); // *should* call the displayBanner function var days = calcDaysToSale(today); // *should* call the function using today's date document.sale.saleMessage.value = days; // *should* set the value to days. // Obviously none of it works. } </script> This is the code working with the script contained in the html file. I'll post the full page at the bottom. The following code is the JavaScript code. The first function isn't made to provide full functionality at the moment, I'm trying to get the rest of it working. Code: function displayBanner(currentDate) { if (currentDate.getMonth() == 2) imgSrc = "winterLogo"; return ("<img src='" + imgSrc + ".gif'>"); } function calcDaysToSale(currentDate) { var saleDay = new Date(); saleDay.setDate(15); // sets the sale date to the 15th of the current month // Subtracts the days remaining until the sale. // If the number is negative, the sale is over. var Days = saleDay.getDate()-currentDate.getDate(); if (Days < 0) { return "The sale has ended."; } else { return Days; } } I have tried to Google the problem and I have also tried to look it up in my book. I simply don't know the right terms to Google, and as I said the book is rubbish. I don't know why the Code: document.sale.saleMessage.value = days; doesn't work for this. Oh well, I'll learn quickly I suppose. Here is the full HTML code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Carol's Flowers</title> <link href="flowers.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="flowers.js"></script> <script type="text/javascript"> function pageSetup() { var today = new Date(); // this creates a date object with today's date var banner = displayBanner(today); // *should* call the displayBanner function var days = calcDaysToSale(today); // *should* call the function using today's date document.sale.saleMessage.value = days; // *should* set the value to days. // Obviously none of it works. } </script> </head> <body class="oneColLiqCtrHdr"> <div id="container"> <div id="header"> <p><img name="myBanner" src="banner" id="myBanner" alt="Carol's Flowers" /> <!-- end #header --> </p> <div id="links"><a href="#">Home</a> | <a href="#">General Arrangements</a> | <a href="#">Seasonal Designs</a> | <a href="#">Custom Orders</a> | <a href="#">Location</a></div> </div> <div id="mainContent"> <table id="mainTable"> <tr> <td width="201"><h1><img src="Flowers.JPG" alt="Random Flowers" width="200" height="255" /></h1></td> <td width="687"> <p>Here at Carol's Flowers, we believe that there is a perfect floral arrangment for every occasion! Take a look around and see if there is anything you like. If we don't already have it, then we will create it for you!</p></td> </script> </tr> </table> <!-- end #mainContent --></div> <div id="footer"> <p> <form name="sale" id="sale"> Days Until Mid Month Madness Sale : <input type="text" name="saleMessage" id="saleMessage" /></form></p> <!-- end #footer --></div> <!-- end #container --></div> <!-- I am trying to run the script here --> <script type="text/javascript"> pageSetup(); </script> </body> </html> Hi All I thought it was about time to actually learn Javascript rather than pretend I know it, so I'm new to Javascript. I've been reading Javascript 'The Good Parts' and have watched a few google videos on Youtube. So I came across prototyping which seems to be quite fundamental to JS but is quite awkward to use. I am trying to avoid the use of the 'new' keyword and limit my application to one Global variable, as this can improve the JS scripts performance, reliability and security. In essence I'm just trying to make a simple MsgBox object that has a method called 'alertMe', which in turn simply shows an alert box with 'Hello' If this is not very clear then say so as trying to explain something you don't fully understand is quite hard. Here's my code, doesn't alert when I called the object. Have a look Code: var MyLib = {}; MyLib.MsgBox = function(){ //Object methods MyLib.MsgBox.prototype.alertMe = function(){ alert('Hello'); }; }; MyLib.MsgBox.alertMe(); Any help and pointers will be very appreciated. Regards, Magnetica Is it possible to create an array of objects? I require a two dimensional array of objects. Thanks! Hello everybody am a JavaScript beginner. here is a code making rollovers //////////////////////////////////////////////// window.onload=rolloverInit; function rolloverInit() { for(var i=0; i<document.images.length; i++) { if(document.images.parentNode.tagName=="A") { setUpRollover(document.images); } } } function setUpRollover(currentImage) { currentImage.outImage = new Image(); currentImage.outImage.src = currentImage.src; currentImage.onmouseout = rollOut; currentImage.overImage = new Image(); var source = currentImage.src; var sourceText = source.toString(); if(sourceText.indexOf("png")>0) { currentImage.overImage.src ="images/"+currentImage.id+"_on.png"; } else { currentImage.overImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.overImage.src ="images/"+currentImage.id+"_on.gif";*/ /*currentImage.overImage.src ="images/"+currentImage.id+"_on.png";*/ currentImage.onmouseover = rollOver; currentImage.clickImage = new Image(); if(sourceText.indexOf("png")>0) { currentImage.clickImage.src ="images/"+currentImage.id+"_click.png"; } else { currentImage.clickImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.gif";*/ /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.png";*/ currentImage.onmousedown = rollClick; currentImage.parentNode.childImage = currentImage; currentImage.parentNode.onblur = rollOutParent; currentImage.parentNode.onfocus = rollOverParent; } function rollOut() { this.src = this.outImage.src; } function rollOver() { this.src = this.overImage.src; } function rollClick() { this.src = this.clickImage.src; } function rollOutParent() { this.childImage.src = this.childImage.outImage.src; } function rollOverParent() { this.childImage.src = this.childImage.overImage.src; } //////////////////////////////////////////////// 1-I do understand "if iam right, lol" that here ///currentImage.outImage = new Image();/// and here ///currentImage.overImage = new Image();/// and here ///currentImage.clickImage = new Image();/// we are creating an image object "overImage" on the fly which still a property of currentImage object, to keep track and store the current image and new image src. but here ///currentImage.parentNode.childImage = currentImage;/// I am unable to see the point behind creating the childImage object -same rule applied here??? is it really a brand new independent object "still a property of the parent" created on the fly like before? and if so -what is is purpose here?? how the cildImage object is interacting here, what is its purpose? and how it is able to modify "actually change" the <a> object child node Image object "currentImage". it seems stupid question but its quiet simple ---///currentImage.parentNode.childImage = currentImage;/// here I have an object on the fly, a new Image object "childImage", that is Fine until now. ---///this.childImage.src = this.childImage.outImage.src;/// now how the childImage became able to change my parent "<A>" child "currentImage" src ??? how it "childImage" became displayable at all is is because of the assignment here ///currentImage.parentNode.childImage = currentImage;/// ??? Yes i assigned currentImage to the childImage, but based on my java programing concepts background each still independent objects refrences representing two different objects ---->and so based on that here is these functions rollOutParent(), rollOverParent() am supposed to say something like ***this.currentImage.src = this.childImage.src*** or ***this.childImage.src = this.childImage.outImage.src;***or whatever "i know thats wrong coding here am just giving example". ------------ am confused, how with this simple line of code currentImage.parentNode.childImage = currentImage; childImage became able to define the currentImage ? and if so, how this was achieved, hoe the Objects is being represented and how they interact in the core memory? |