JavaScript - Date Object - Need Value Assignment Not Reference
The goal is for selectedDay to be assigned the value of the system variable Mainpackage.subclass0.subclass1.firstDay and then incremented by two days. Mainpackage.subclass0.subclass1.firstDay needs to be unchanged.
Important system variable in red. To be 'manipulated and used' variable in green. Even with an intermediary, third, dummy variable it doesn't work: Code: //Declarations and instantiations var systemDate = new Date(); var selectedDay = new Date(); Mainpackage.subclass0.subclass1.firstDay ; //Assignments and manipulations systemDate = Mainpackage.subclass0.subclass1.firstDay ; selectedDay = systemDate ; selectedDay .setDate( selectedDay .getDate()+2); //Logging console.log('Mainpackage.subclass0.subclass1.firstDay: ' +Mainpackage.subclass0.subclass1.firstDay +'\n' +'systemDate: ' +systemDate +'\n' +'selectedDay :' +selectedDay +'\n'); Console log is: Code: Mainpackage.subclass0.subclass1.firstDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) systemDate: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) selectedDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) It doesn't work in my webapp : All variables change at the same time. Similar TutorialsMy question is commented in the script: Code: function Love(){ var req = { ring : 'gold', money : 'a lot', commitment : 'long-term' } this.loveReqs = function(){ return req; } } var you = new Love(); var details = you.loveReqs(); details.ring = "silver"; console.log(details.ring); var me = new Love(); var details = me.loveReqs(); console.log(details.ring); // why does this return gold and not silver if req is passed by reference and we already changed its value above and so it's pointing to the same memory position? Hi, I have this ajax routine... Code: function xhr_get(target_str,async){ var sync=true; if(async){sync=false;} var xhr = new XMLHttpRequest(); xhr.open('GET', target_str, sync); if(sync==false){ xhr.onreadystatechange = function () { if (xhr.status === 200) { try{ var ii =JSON.parse(xhr.responseText);} catch (exception) { } if(ii){ return ii; }else{ alert(xhr.responseText); return false; } } else { alert(xhr.status+' '+target_str);return false; } }; xhr.send(null); }else{ xhr.send(null); try{ var ii =JSON.parse(xhr.responseText);} catch (exception) { } if(ii){ return ii; }else{ alert(xhr.responseText); return false; } } } now if I alert(ii) on success the data I am looking for (specifically ii.content) shows up in the alert as expected however when calling from another javascript function, ii is false ???? please explain, Code: function call_change_val(fld,vm_id){ var str='?_f=load_edit_fld&_ctl_fld='+fld+'&vm_id='+vm_id+'&fld='+fld+'&width=80'; i = xhr_get('ajax/val_main_loader.php'+str,true); ////////////////////// alert(i); or alert(i.content) here both give be a blank popup///////////////// showdiv('c_change_'+fld); setih('c_change_'+fld,i.content); } I expected alert(i) to say Object or similar, getting nothing I am confused about what the return keyword is actually returning when returning an object, a primitive, or a function. My confusion is compounded by the fact that I'm not sure if a function is an object or not. According to the book JavaScript Programmer Reference it is: "All functions in JavaScript are first class objects , meaning they can be passed around like any other object reference. In fact, regardless of how they are created, functions are instances of a global object named (aptly) Function." However, someone else states that a function is not an object. An object is a set of primitives and references. A function is executable code. Functions become objects through the use of the new operator. Yet, in the book I mentioned, it says you don't need the new keyword to execute the function as an object, as it already inherits from the object Function when the function keyword is used: Code: function functionName([argname1 [, ...[, argnameN]]]) { statements; } So there's one source of contradiction. Now the bigger issue is what is going on when the return keyword is used. Notice the Validation() function returns an object as its last expression. This technique is common, where you return an object which contains functions in form of object notation. I believe this is done so that we create a closure so that when the intepreter exits the Validation() method, since we created a closure by returning an object, which contains the inner functions addRule and getRule, the local variables of Validation() are not destroyed, given that we can reference them through the two inner functions that make use of the local variables of the outer function. So when we use the return keyword on an object literal, and then exit the function, when we call one of the inner functions as we do later: Code: var rule = $.Validation.getRule(types[type]); essentially getRule() is called, passes an argument, which is received by the inner function as parameter we call name: Code: getRule : function(name) { return rules[name]; } First, note that the return {} is written in object notation, therefore making getRule a local variable and, thus, private function only accessible through the namespace of Validation(). Validation() declares the rules local variable and because of the closure, we can access the rules local variable through the getRule() inner function. *****Here's the part that really thows me off. We return rules[name]. So let's say name is equal to email. This is an associative array so email (held in name) is a property of rules. So here we return the object's property: Code: return rules[name]; And then assign it to a local variable called rule: Code: var rule = $.Validation.getRule(types[type]); So when we return an object rules[name], do we return a reference to an object or a value? In other words, by returning rules[name], where name is equal to email, are we then returning a reference to the following object literal: Code: email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." } And if we are returning a reference, by returning a reference, are we essentially pointing to this object when we assign it to rule? In other words, the variable rule is just pointing to the object literal? And is that the reason we can then access the check function or msg local variable through rule using dot notation, because rule points to the email object literal? Now the ultimate brain twist for me is that if a function is an object, then why when return a function, it returns a value, such as a boolean, if an object only returns a reference and not the value? Code: //Validation is a local variable as it is in a self-executing anonymous function. The purpose of the said anonymous function is to pass the jQuery object as a parameter $ so the $() function will be in scope of the anonymous function and not interfere with other libraries that make use of the same function technique - in the global scope. (function($) { var rules = { email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." }, url : { check : function(value) { if(value) return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?"); return true; }, msg : "Enter a valid URL." }, required : { check: function(value) { if(value) return true; else return false; }, msg : "This field is required." } } var testPattern = function(value, pattern) { var regExp = new RegExp("^"+pattern+"$",""); return regExp.test(value); //The test() method is built into javascript } return { addRule : function(name, rule) { rules[name] = rule; }, getRule : function(name) { return rules[name]; } } } /* Form factory */ var Form = function(form) { var fields = []; $(form[0].elements).each(function() { var field = $(this); if(field.attr('validation') !== undefined) { fields.push(new Field(field)); } }); this.fields = fields; } Form.prototype = { validate : function() { for(field in this.fields) { this.fields[field].validate(); } }, isValid : function() { for(field in this.fields) { if(!this.fields[field].valid) { this.fields[field].field.focus(); return false; } } return true; } } /* Field factory */ var Field = function(field) { this.field = field; this.valid = false; this.attach("change"); } Field.prototype = { attach : function(event) { var obj = this; if(event == "change") { obj.field.bind("change",function() { return obj.validate(); }); } if(event == "keyup") { obj.field.bind("keyup",function(e) { return obj.validate(); }); } }, validate : function() { var obj = this, field = obj.field, errorClass = "errorlist", errorlist = $(document.createElement("ul")).addClass(errorClass), types = field.attr("validation").split(" "), container = field.parent(), errors = []; field.next(".errorlist").remove(); for (var type in types) { var rule = $.Validation.getRule(types[type]); if(!rule.check(field.val())) { container.addClass("error"); errors.push(rule.msg); } } if(errors.length) { obj.field.unbind("keyup") obj.attach("keyup"); field.after(errorlist.empty()); for(error in errors) { errorlist.append("<li>"+ errors[error] +"</li>"); } obj.valid = false; } else { errorlist.remove(); container.removeClass("error"); obj.valid = true; } } } /* Validation extends jQuery prototype */ $.extend($.fn, { validation : function() { var validator = new Form($(this)); $.data($(this)[0], 'validator', validator); $(this).bind("submit", function(e) { validator.validate(); if(!validator.isValid()) { e.preventDefault(); } }); }, validate : function() { var validator = $.data($(this)[0], 'validator'); validator.validate(); return validator.isValid(); } }); $.Validation = new Validation(); })(jQuery); Thanks for any response. I am trying to use my date Object function to get the date from the comp but my variables in my function are coming up undefined. Here is my function: Code: function displayTime() { var currentTime, hour, minute, second, range, m, s currentTime = new Date() var hourInt = currentTime.getHours() var minuteInt = currentTime.getMinutes() var secondInt = currentTime.getSeconds() if (hourInt > 12) { range = "PM" hourInt -= 12 } else { range = "AM" } hour = String(hourInt) if (minuteInt < 10) { m = String(0) + String(minuteInt) } minute = m if (secondInt < 10) { s = String(0) + String(secondInt) } second = s document.timeForm.timeBox.value = hour + ":" + minute + ":" + second + " " + range alert(hour + ":" + minute + ":" + second + " " + range) I appreciate the help This is my first post... and a quick question that is mostly likely easy for most of you!! I am pulling in some data from an MySQL database and generating a graph using RGraph and some HTML. The date pulled in is shown as 2011-01-01 for example. I would like to simply format the date and turn into Jan, 01, 11 or similar. Any recommendations on using Date Object to format that in to the date text? Hey guys, this is an assignment for school. I have most of the code done but I cant figure out how to completely finish one part of the assignment. I bolded the part in which i'm having trouble with. Heres the Directions per the Instructor: Create a new HTML document that creates a listing of the days and date for the current month. 1. Create a new array, named monthArray that holds the names of the all of the months in a year, i.e. January, February… 2. Create a new array, named weekDaysArray that holds all of the days of the week, i.e. Sun, Mon, Tue,…. 3. Get today’s date by using the Date object, without initializing a value for the object and save it in a variable named todaysDate. a. Using the Date object methods, break up the value of todaysDate into variables that hold each of the pieces of the date, by assigning the values to the following variables: (see page 169 in text) i. currYr = year ii. currMon = month as an integer iii. currDate = day of the month iv. currDay = the day of the week as an integer 4. Use a document.write statement display the name of the month followed by the 4 digit year. (i.e. October 2011) a. Use currMon as the index to get the name of the month from the monthArray created in step 1. b. Use the variable currYr created in step 3. c. Include a blank line after this displayed line 5. Determine the name of the first day of the current month. a. Using the correct Date Object method, get the integer for the day of the week for the first day of the current month. (hint: you will need to pass the year, month and the day value of 1 to the Date Object to get this number) 6. Use a document.write statement to display every day of the current month on a new line in the format of the name of the day followed by the integer for the date. a. Use a while loop to keep track of the number of days written for the month. b. Use a for loop to write out the days of the week from the array created in step 2 under the name of the current month and year. Example output: October 2011 Sat 1 Sun 2 Mon 3, etc….until all 31 days are displayed. My Code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Assignment 9</title> <script type="text/javascript"> var monthArray = new Array ("January","February","March","April","May","June","July","August","September","October","November","December"); var weekDaysArray = new Array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"); var todaysDate = new Date(); var currYr = todaysDate.getFullYear(); var currMon = todaysDate.getMonth(); var currDate = todaysDate.getDate(); var currDay = todaysDate.getDay(); document.write(monthArray[currMon] + " " +currYr); document.write("<br />"); document.write(weekDaysArray[currDay] + "<br />"); var count = 0; while (count < 31) { count++; } for(var count = 0 ; count < 31 ; count++) { document.write(weekDaysArray[count]+ "<br />"); } </script> </head> <body> </body> </html> Hi, My JS Date validation was failing for a date which as per business is a valid date (01/01/0001) - MM/DD/YYYY It seems that the constructor for Date object is doing something funny.. var dayobj = new Date(yearfield, monthfield-1, dayfield) wasn't working for this case whereas teh one mentioned below seems to be working fine : var dayobj = new Date() dayobj.setFullYear(yearfield,monthfield-1,dayfield) What's the trick here ?? As you can see in the attached Firebug screen capture, I am setting up a new Date object with "2011", "4", "23" but in the watch window you can see it is setting up the date object with a month of May instead of April. I also tried 2011, 4, 23 (no quotes) and no improvement. What am I missing? Hi Script Experts I am facing issue in below code for Brisilia time zone.(GMT-3). Issue comes in October month only. It is going tobig loop. I am not getting how Date object is behaving here. Thanks in advance Pranav Sharma *********************************** <script type="text/javascript"> var nDate; var nCurrentYear = 2011; var nCurrentMonth = 10; nYear=2011; nMonth=10; var date = new Date(nYear, nMonth-1, 1); document.write('Month:'+date.getMonth() +':CurrentMonth:'+nCurrentMonth); while (date.getMonth() == nCurrentMonth-1) { nDate = date.getDate(); document.write(date.toDateString()); date = new Date(nCurrentYear, date.getMonth(), date.getDate()+1); } </script> ********************************** http://i50.tinypic.com/2njcxn5.png basically.. a button that changes the color of that box.. the font to bold.. and changes a frame from two search engine websites. Hello, in semester 2 of my first year of a Business Computer Systems. Anyway for my recent assignment I need to build a pretty basic shopping cart and have some cilent side validation as well. ----------------------------------------- Shopping Cart Anyway for the shopping cart do i have to: Item = goes into its own array Amount = goes into its own array price = goes into its own array then use a retrieve function to add each array into different sections in a table. and then simply times the amounts by their prices then add them all together using for loops? or can Item Amount = All in the same array. Price Then use a for loop to detect the correct data from the array for each section of the shopping cart? ----------------------------------------- Client Side Validation Presumably I just use simply javascript to detect phone numbers within a box form. i.e. (in simply english) if amount in phone form is < 11 then display alert. same for @ and . for email address? Hi, I have been working on a CS assignment that pertains to calculating the total cost (including tax) once a certain item is bought (there are a total of 4 different products). I can't get the code to work, so any help is much appreciated. Thank you. Question: Create a Web page that contains 1 text field and 1 button. The text field will be used to display the product/service ordered. Use a prompt window to get the user's name. Convert their name to proper case. Use an alert window to display a welcome message that includes their name. Use a prompt window to ask the user which one of four products/services they wish to purchase. Based on their input, calculate the tax and total cost for this product/service. Display the product/service ordered in the proper field. Then create bill. At the end, use the an alert window to display a message telling the user to click the browser's Back button to reload the page to start again. Code so far: Code: <html> <head> <title> Android World Products </title> <script type="text/javascript"> <!-- var fullName = ""; function askName() { fullName = prompt("Please Enter Your Name:"); var x = fullName.indexOf(" "); var firstName = fullName.substring(0,x); firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1); var lastName = fullName.substring(x+1); lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1); fullName = firstName + " " + lastName; if (x > -1) alert("Welcome " + fullName); else alert("Please try again."); } var evoPrice = 250.00; var optimusPrice = 200.00; var captivPrice = 150.00; var casePrice = 30.00; var products = new Array('HTC Evo 4G','LG Optimus S','Samsung Captivate','Leather Case'); var prices = new Array(evoPrice,optimusPrice,captivPrice,casePrice); var tax = 1.08375; var totalCost = 0; if(product==1) {totalCost = evoPrice + (evoPrice*tax); } else if(product==2) {totalCost = optimusPrice + (optimusPrice*tax); } else if(product==3) {totalCost = captivPrice + (captivPrice*tax); } else if(product==4) {totalCost = casePrice + (casePrice*tax); } return totalCost; } var seeBill = confirm("Click OK to See Your Bill"); if(seeBill) { Window = window.open("","Receipt","width=200,height=200"); Window.document.write("Android World <br>"); Window.document.write("Customer Name: "+Name+"<br>"); if(product=="1") {Window.document.write("Product: "HTC Evo 4G"<br>"); Window.document.write("Cost: $"evoPrice"<br>"); } else if(product=="2") {Window.document.write("Product: "LG Optimus S"<br>"); Window.document.write("Cost: $"optimusPrice"<br>"); } else if(product=="3") {Window.document.write("Product: "Samsung Captivate"<br>"); Window.document.write("Cost: $"captivPrice"<br>"); } else if(product=="4") {Window.document.write("Product: "Leather Case"<br>"); Window.document.write("Cost: $"casePrice"<br>"); } Window.document.write("Tax: 8.375%<br>"); Window.document.write("Your total cost for this purchase: $"totalCost"<br>"); Window.document.write("Thank you for shopping at Android World!"); function show_prompt() <input type=button value="Try it now" onClick="alert('Please use the browser's back button to reload the page')"> </script> </head> <body onload="askName ()"> <body style="background-color:#66FF66"> <h1> Android World Products </h1> <ol>Offered Products: <li>HTC Evo 4G: $250.00</li> <li>LG Optimus S: $200.00</li> <li>Samsung Captivate: $150.00</li> <li>Leather Case: $30.00</li> </ol> <br> <!--form name="Form" action="" method=""> <br> <input type="text" name="customer" onclick="typename()" /> <input type="button" name="" value="Confirm Your Purchase" onclick="" /> </form> </body> </html> First of all, Who's the best Javascript here?
Here is the assignment: Ocean Levels Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the ocean will have risen each year for the next 25 years. (we should use a "for" loop) Here is my code so far: <html> <head> <title>Ocean Page</title> <script type = "text/javascript"> var year, rise; document.write("Number of Years Ocean Level <br />"); year_str = alert("This will give you the prediction of ocean level rise for up to 25 years", ""); year_str= 25 year = parseFloat(year_str); rise_str = alert("The Ocean Rises at 1.5 milimeters a day", ""); rise_str = 1.5 rise_str = parseFloat(rise_str); r= parseFloat(rise_str) var MAX_VALUE = r; for (rise=1; rise <= r; ++rise ) { distance = rise * year document.write(year+" years   "+ distance+" ocean level <br />"); } </script> </head> <body> <h3>Click Refresh (or Reload) to run the script again</h3> <br /> </body> </html> END So far it just gives me years 25 ocean level 25. I can probably figure out how to create a table...but I'm having an issue getting the 1.5 to multiply 25 times. Any help? I'm a newby =) Thanks a million!!!!!!!!!!!! =) OK Once again not out to spam . I am confused on this assignment? this is what i need to do The Sieve of Eratosthenes An integer is a prime number if it is evenly divisible by only itself and 1. There are several ways to find all prime numbers within a given range of integers, and the Sieve of Eratosthenes is an algorithm for to do just that. It operates as follows: Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will remain as 1. All other array elements will eventually be set to zero. Starting with array subscript 2 (subscript 1 must be prime), every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all elements beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for array subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.); and so on. When this process is complete, the array elements that are still set to 1 indicate that the subscript is a prime number. These subscripts can then be printed. Write a script that uses an array of 1000 elements to determine and print the prime numbers between 1 and 999. Ignore element 0 of the array. Ok for anyone who may understand, what am i supposed to create as output? Am i supposed to get a one big chart of numbers? or do i get a forever flow of numbers? suggestions please I am not really looking for code, just want some idea of what am i supposed to make as output? thanks Hey there, so this is my first time using this website. I was wondering if anyone can help me resolve this problem. It is for my Website Development Class and I am going use this forum to help me understand the languages haha. But Anyways. My homework assignment I have to do is: Create a Web page named gpa.html that can be used to compute your grade point average given grades and hours for courses completed. The page should repeatedly prompt the user for course information, reading the course name, grade received, and credit hours for a particular course in a single dialog box. While the user is done inputting the information, it should display on the website like this: COURSE GRADE HOURS THL100 B+ 3 PHL107 A 3 ENG120 C+ 3 MTH245 A 4 CSC221 A 3 Total grade points = 58 Number of hours = 16 GPA = 3.625 So my problem is that when I tried to display it outside the while loop it only displays "NaN". Please Help and Thanks! Here is my code: <!DOCTYPE html> <html> <!-- gpa.html--> <head> </head> <body> <script type= "text/javascript"> document.write("Course - Grade - Credit Hours"); document.write("<br>"); var third; var total = 0; var total2 = 0; var total4 = 0; var t_hrs = 0; var user; while (user != "") { user = prompt("Hello User. Enter course name, grade, & credit hours (i.e CS3240 B+ 3), or click OK with no data to terminate."); var uInput = user.split(" "); document.write(uInput); document.write("<br>"); third = uInput[2]; t_hrs = parseInt(t_hrs) + parseInt(uInput[2]); if (uInput[1] == "A"){ letter2point = 4.0; } else if (uInput[1] == "B+"){ letter2point = 3.5; } else if (uInput[1] == "B"){ letter2point = 3.0;} else if (uInput[1] == "C+"){ letter2point = 2.5; } else if (uInput[1] == "C"){ letter2point = 2.0; } else if (uInput[1] == "D"){ letter2point = 1.0; } else if (uInput[1] == "F"){ letter2point = 0.0; } total = letter2point * third; total2 = total2 + total; total4 = total2 / t_hrs; } document.write(total4) </script> </body> </html> Reply With Quote 01-29-2015, 02:47 AM #2 felgall View Profile View Forum Posts Visit Homepage Master Coder Join Date Sep 2005 Location Sydney, Australia Posts 6,745 Thanks 0 Thanked 666 Times in 655 Posts If that antiquated JavaScript is what your course is teaching then I feel sorry for you. Just about every statement that you have there is listed on one of the "Bad Bits" pages of my Introducing JavaScript web site where it gives the reasons for not using those 20 year old code constructs in modern web browsers (which means IE5 and any browser more recent than that). A couple of suggestions to get you started. 1. The second document.write is not complete so everything from there onward is broken. 2. To convert to a number use Number((t_hrs) or (+t_hrs). If you must use parseint then always include the second parameter to specify the number base you are converting from parseInt(t_hrs, 10) - with regard to t_hrs it is a number to start with so doesn't even need this conversion. 3. Use === and !== instead of == and != as the two character versions don't always give the expected result where the three character versions always do. |