JavaScript - Calculating Number Of Days For Leave Management In Js
Hi, i have just started learning & understanding JavaScript.
I am just trying to do a small project for my Brother regarding Leave Management, for which its required to Select the From Date & To Date, wherein the Total no. of days should be calculated, excluding the weekends. I have just worked around to calculate the number of days but i am not sure how to exclude the Weekends. & what if the the Year is a Leap year - So how will i include the Extra days of Feb month. I am using RAD date-pickers to get the Value & split it. But being a newbie to the Coding world i m really N'joyin the JavaScript.... Just need help regarding this coz i m totally helpless... I am taking the 2 Dates from 2 Rad Datepickers & diplaying the Number of Days in a Text Box. Here is My Coding :- Code: <script type="text/javascript"> function CalcLeaveDays() { var FromDate=document.getElementById("ctl00_ContentPlaceHolder1_ApplyLeaveNew_control_rdpStartdate"); var ToDate=document.getElementById("ctl00_ContentPlaceHolder1_ApplyLeaveNew_control_rdpEnddate"); document.getElementById("ctl00_ContentPlaceHolder1_ApplyLeaveNew_control_txtnoofdays"); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; var FrmDate=FromDate.value.substring(8,10); var FrmMonth=FromDate.value.substring(5,7); var FrmYear=FromDate.value.substring(0,4); var TDate=ToDate.value.substring(8,10); var TMonth=ToDate.value.substring(5,7); var TYear=ToDate.value.substring(0,4); var sysDate=new Date(); var sysDay=sysDate.getDate(); var sysMonth=(sysDate.getMonth())+1; var sysYear=sysDate.getFullYear(); var LeaveDays; if(FrmYear>=sysYear) { if((FrmMonth>=sysMonth)&(TMonth>=sysMonth)) { if(FrmDate>(sysDay+3)) { if(TDate>=FrmDate) { if(FrmDate==TDate) { alert ('1') LeaveDays = 1; } else if(TDate>FrmDate) { alert(TDate-FrmDate+1); LeaveDays = TDate-FrmDate+1; } else { alert('Check'); return false; } } else { alert('Kindly Select the End Date Appropriately '); return false; } } } } document.getElementById("ctl00_ContentPlaceHolder1_ApplyLeaveNew_control_txtnoofdays").value =LeaveDays; } </script> Similar Tutorialshey guys, happy new year! , I was wondering how to calculate an outcome/number through a combination of 4 drop down menus (drop down menu's 1 and 2 combine to form a specific value and menu's 3 and 4 combine to form a specific value), example ; 1st drop down menu (1*) = a,b,c,d,e 2nd drop down menu (2*) = 5,4,3,2,1 3rd drop down menu (3*)= a,b,c,d,e 4th drop down menu (4*)= 5,4,3,2,1 Example of drop down menu layout - View image: example a->e = low to high (value) predominant value so b5>a1 ; d5>c1 5->1 = low to high (value) Then the calculation involves the 1st and 2nd menu to form 1 value, so c3, e4 etc and the 3rd and 4th menu unite to form 1 value that is different from the first; c2, e3 So (1*2*) b3 ; (3*4*) b1 = x value Also the value from 1*2* menu must be lower than value from menu 3*4*; so you cannot input 1*2* c4 ; 3*4* c5 /or b1 (so once the first menu is selected, the 3rd and 4th menu's wont show anything lower) I am not sure the best way about going to calculate the value for x (generated from the menu combinations) however I can outline the values for each combination as it involves simple addition; Example; 1*2* c5 ; 3*4* c4 = 39 Example; 1*2* c4 ; 3*4* c3 = 43 Example; 1*2* c3 ; 3*4* c2 = 44 Example; 1*2* c2 ; 3*4* c1 = 49 Therefore 1*2* c5 ; 3*4* c1 = 175 (c5>c4 + c4>c3 + c3>c2 + c2>c1 = 175) Starting from a5 to e1 the values are as follows; [(a5->a4 = 17),17,17,17],[(a1->b5 = 22.5),22.5,22.5,22.5],[39.6,39.6,43,44],[49,56.7,56.7,60],[69,76.5,90,161],[189.5,216,(e2->e1 = 246.5),no further value (no f5)] If you could help me out that would be amazing, appreciate any help/feedback in advance! I would like to take this timeout: Code: setTimeout("hidediv('layer')", 2000); And activate only when the mouse leaves the DIV and de-activate when the mouse comes back in. Is this possible and how? What are those events? Hi, I need to a small task in Javascripts and I would like to know whether this can be done. If someone knows a way that can be done or provide me some code, I would be more greatful. This is the task I need to do :- I have a small shoppig cart. I want when a customer visit the site, if that is his first time on the website and before he quit the browser or go to another URL of another domain or press back and go to another page, an alert should pop up. I have did this using cookies and Javascripts and it is working properly as I wanted. But this alert pops up even when I go inside of my own web. I want this alert only to popup when they leave from my web or go to anyother and it should not popup when I click on my links or go in to my web. I hope, I explained what I want and it is clear. Please if someone knows a solution for this. Please send me your ideas or if you have some codes that can be helpfull to me, please send me. Thank you. Hello, I've made a scrollable image gallery. I need the big image to pop up when the thumbnails are hovered over. It works fine in Firefox but in IE the big image fails to disappear when you take the mouse off the thumbnail. Please could someone look at this jquery code for me I am new to this someone made this for me but it really needs to work in IE too. Many thanks for your time emmamargaret <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $(".scrollable").scrollable({ vertical: true, mousewheel: true }); var container = $("#imagewrap"), content = $("#centrecontainer"); $(".items img").bind("mouseenter mouseleave", function(e) { var thumb = $(this); if (e.type == 'mouseenter') { container.css({backgroundImage: "url(http://www.emmagallagher.co.uk/" + thumb.attr("src") + ")"}); } else { container.css({backgroundImage: none }); } content.toggle(e.type == 'mouseleave'); }); }); var MM_swapImage = MM_swapImgRestore = function() {}; </script> The topic of event handler management has been covered in many places in the past. One location is in the contest by PPK. The winning submission by John Resig has a few problems, and the commentary on the site seems to gravitate to the implementation by Dean Edwards after the analysis of the Resig code. I was also able to find a few more implementations on stackoverflow from: Bill Ayakatubby and Marco Demaio. Outside of the JavaScript frameworks, what is generally done for supporting event functionality? There are numerous options each with their own benefits and drawbacks. I'm uncertain of which one to use myself. Is there an undeclared de facto? I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } When I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
I now have the calculation, topic can be closed! thanks Hi, I am trying to write a script that will take a date of birth and another date and, if the person was over 75 years old on the createdDate, return "true" (otherwise return "false"). Unfortunately my code doesn't seem to return either 'true' or 'false'! Any help would be grately appreciated. The code is: Code: var dateofBirth="30/10/1982"; var createdDate="01/12/2010"; var sd = dateofBirth.split('/'); var dob = new Date(sd[2],sd[1],sd[0]); sd = createdDate.split('/'); var submit = new Date(sd[2],sd[1],sd[0]); var age=submit-dob; var ageYears=Math.floor((((age/3600000)/24)+1)/365.25); if(ageYears>75) document.write("true") else document.write("false") ; Hi, There are two text boxes in a HTML form. The first text box takes the time when the user starts to work on a project. The second box takes the time when the user stops working on that project. Now, I would like to calculate the total time worked on that project for that user. That is (stop time - start time). I tried few things without success. Any help will be appreciated. to be honest I have no idea where to start, i have a table, with 2 numeric values at the minute, if the checkbox is selected I want the total price to be shown? Any help to get me started would be great! this is the form I have with the numeric values Code: <form id="calculation" action="#" method="post"> 100 <input type="checkbox" name="check1" value="100" onClick='total_cost()'/> 120 <input type="checkbox" name="check2" value="200" onClick='total_cost()'/> Total cost<input type="text" name="total" id="total" readonly="readonly" /> onClick='total_cost()' is referring to the javascript function where I just don't know where to start? Hello everyone. Below is code I have developed for a simple spreadsheet. The issue I am having is that when I total a row or column using "=sum(a1:a5)" and then I try and total another row and add the sum of the two totals together I am not getting a valid response back. All I am presented with is a "0" in the column cell. Here is the code in two files and have also included an attachment of the whole project: tablepage.js Code: // JavaScript Document var tblRows = 20; var tblColumns = 10; var tblArray = new Array(tblRows); var p = window.parent; // Initial page event handler function initPage() { p.refAssignCellFromTextbox = assignCellFromTextbox; for (var i = 0; i < tblArray.length; i++) { tblArray[i] = new Array(tblColumns); for (var j = 0; j < tblArray[i].length; j++) tblArray[i][j] = "0"; } recalculate(); } // Recalculate cell values function recalculate() { for (var i = 0; i < tblRows; i++) { for (var j = 0; j < tblColumns; j++) { if (tblArray[i][j].indexOf("=SUM") != -1) { calculateCell(i, j); } } } } // Click cell event handler function clickCell(cellRef) { thisRef = cellRef; var cellID = cellRef.id; var row = parseFloat(cellID.substr(0, 3)) - 1; var column = parseFloat(cellID.substr(3, 2)) - 1; var cellValue = tblArray[row][column]; var tokenArray = getFormula(cellValue); if (tokenArray != null) p.assignTextboxFromArray(cellValue); else p.assignTextboxFromCell(cellRef); } // Update cell from textbox function assignCellFromTextbox(tblValue) { if (thisRef != undefined) { if (tblValue == "") { tblValue = "0"; } var tokenArray = getFormula(tblValue); if (tokenArray != null) { assignArray(thisRef.id, tblValue.toUpperCase()); } else { if (!isFloat(tblValue)) { parseValue = tblValue.replace(/[^0-9]/g, ''); tblValue = parseValue; } assignArray(thisRef.id, tblValue); if (tblValue == "0") thisRef.innerText = ""; else thisRef.innerText = tblValue; } recalculate(); } } // Determines if a user entered a formula function getFormula(tblValue) { var pattern = /[:|\(|\)]/; var ar = tblValue.split(pattern); var sum = ar[0].toUpperCase(); if (ar.length < 3) return null; else if (sum != "=SUM") { return null; } else { return ar; } } function assignArray(cellID, tblValue) { var row = parseFloat(cellID.substr(0, 3)); var column = parseFloat(cellID.substr(3, 2)); tblArray[row - 1][column - 1] = tblValue; } function calculateCell(row, column) { var tokenArray = getFormula(tblArray[row][column]); if (tokenArray != null) { var fromColumn = tokenArray[1].substr(0, 1); var fromRow = tokenArray[1].substr(1, tokenArray[1].length - 1); var toColumn = tokenArray[2].substr(0, 1); var toRow = tokenArray[2].substr(1, tokenArray[2].length - 1); var fromRowIndex = parseFloat(fromRow) - 1; var fromColIndex = fromColumn.charCodeAt(0) - 65; var toRowIndex = parseFloat(toRow) - 1; var toColIndex = toColumn.charCodeAt(0) - 65; var sumTotal = 0; for (var i = fromRowIndex; i <= toRowIndex; i++) { for (var j = fromColIndex; j <= toColIndex; j++) { if (isFloat(tblArray[i][j])) sumTotal += parseFloat(tblArray[i][j]); } } var cellID = fillField((row + 1).toString(), 3) + fillField((column + 1).toString(), 2); document.getElementById(cellID).innerText = sumTotal; } } function isFloat(s) { var ch = ""; var justFloat = "0123456789."; for (var i = 0; i < s.length; i++) { ch = s.substr(i, 1); if (justFloat.indexOf(ch) == -1) return false; } return true; } function fillField(s,n) { var zeros = "0000000000"; return zeros.substring(0, n - s.length) + s; } spreadsheet.js Code: // JavaScript Document var refAssignCellFromTextbox; var nCharsAllowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.=(): "; // Event Handler function initPage() { document.getElementById("TableFrame").style.top = "50px"; document.getElementById("TableFrame").src = "tablepage.html"; } // Updates text field when a user clicks on a particular field from with the spreadsheet function assignTextboxFromCell(cValue) { document.getElementById("fieldEntry").value = cValue.innerText; document.getElementById("fieldEntry").focus(); } // Assists tablepage.js with updating a value from a 2D array function assignTextboxFromArray(aValue) { document.getElementById("fieldEntry").value = aValue; document.getElementById("fieldEntry").focus(); } // Used when a user presses a key to update text field function filterText() { if (window.event.keyCode != 13) { if (!nCharOK(window.event.keyCode)) window.event.keyCode = null; } else { window.event.keyCode = null; refAssignCellFromTextbox(document.getElementById("fieldEntry").value); } } // Checks to see if character entered falls within our preset function nCharOK(c) { var ch = (String.fromCharCode(c)); ch = ch.toUpperCase(); if (nCharsAllowed.indexOf(ch) != -1) return true; else return false; } // Clears all data from the screen function clearPage() { initPage(); document.getElementById("fieldEntry").value = ""; } // Add a row to the table function addRow(frmTable) { var table = document.getElementById(frmTable); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); // cell2.innerHTML = rowCount + 1; // Unless this is going to be completely dynamic // the rest of the table code would have had to be // entered in statically. Not happening. } // Delete a row from the table function deleteRow(frmTable) { try { var table = document.getElementById(frmTable); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { table.deleteRow(i); rowCount--; i--; } } } catch(e) { alert(e); } } Hi guys Sorry about the vague Title, but I really do not know anything about JavaScript. Infact I only know very VERY basic html... So I hope you can help me. I am trying to create a form like this: Where the blue is user entered, and red is results. Apparently I can't do that with my basic html skills but javascript can? The Formula via excel for 'Generic SOP' is =100-((ABS(A3-10))+(ABS(B3-10))+(ABS(C3-10))+(ABS(D3-10))+(ABS(E3-10))+(ABS(A6-10))+(ABS(B6-10))+(ABS(C6-10))+(ABS((D6-20)/2))+(ABS(E6-10))) and for 'SOP' =100-((ABS(A3-10)*1.5)+(ABS(B3-10)*1)+(ABS(C3-10)*1)+(ABS(D3-10)*2)+(ABS(E3-10)*1)+(ABS(A6-10)*0.5)+(ABS(B6-10)*0.5)+(ABS(C6-10)*1)+(ABS(D6-20)/2)+(ABS(E6-10)*0.5)) I would also like a drop down box that allows me to choose different variables that changes the 'SOP' formula slightly.. but maybe I should leave that out for now.. I hope that was understandable and if this is too much to ask just tell me to get nicked and go learn how to code myself.. Thankyou for looking guys Calculating the difference between two dates in JavaScript is relatively straightforward, provided you choose the right Date methods to work with. Whichever way you get there.... see this http://www.tutorials99.com/tutorials...aScript/page_1 I'm trying to find the difference between 2 times. Time formats are 00:00:00.0 For example... var t1 = "00:07:51.0"; var t2 = "00:53:21.0"; How do I calculate the difference between those 2 times? TIA. I am having difficulty getting the following assignment to run properly: Many companies charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minmum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Save the document as CalcShipping.html. This is what I have after working on it round and round for 4 hours yesterday: <!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"> <head> <title>Calculate Order</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="js_styles.css" type="text/css" /> <script type="text/javascript"> /* <![CDATA[ */ function applyShipping(shipping) { if (purchase > 25.00) shipping = purchase * 10 / 100; } /* ]]> */ </script> </head> <body> <script type="text/javascript"> /* ![CDATA[ */ document.write("<h1>Purchase Plus Shipping</h1>"); /* ]]> */ </script> <script type="text/javascript"> /* <![CDATA[ */ var purchase=window.prompt("Please Enter Your purchase amount"); var shipping = 1.50; applyShipping(); document.write ("<p>The price entered was $" + (purchase) + "</p>"); document.write ("<p>Shipping and Handling $" + (shipping) + "</p>"); var totalPrice = purchase + shipping; document.write ("<p>Your total price is $" + (totalPrice) + "</p>"); // window.alert("Your total price is $" + (totalPrice) + );// /* ]]> */ </script> </body> </html> I thought this would be simple. Evidently it's not With the date below (and it being 11.45 on the 27th as I type this), the counter returns the correct number of hours/mins/seconds remaining, but shows 33 days. It seems to be adding 31 days to the count, but I can't figure out where Code: function countdown(){ var bigday = new Date(2009,10,29,14,30,0,0); var today = new Date(); var difference = bigday - today; var remaining = Math.floor(difference/1000); // want seconds, not milliseconds var days = Math.floor(remaining/86400); remaining = remaining % 86400; var hours = Math.floor(remaining/3600); remaining = remaining % 3600; var minutes = Math.floor(remaining/60); remaining = remaining % 60; seconds = Math.floor(remaining); var out = days + " days, " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds left..."; $('#countdown').text(out); setTimeout(countdown, 1000); } Hey there, first time poster. I am trying to create an order with the ability to dynamically self total the sum of the selected items but also be able to add a 25% labor fee having it be at least $90. So if someone buys $300 worth of items the labor charge would be $75 but it would be automatically bumped to $90. heres the existing code: PHP Code: * Calculates the payment total with quantites * @param {Object} prices */ countTotal: function(prices){ var total = 0; $H(prices).each(function(pair){ total = parseFloat(total); var price = parseFloat(pair.value.price); if ($(pair.key).checked) { if ($(pair.value.quantityField)) { price = price * parseInt($(pair.value.quantityField).getSelected().text, 10); } total += price; } }); if (total === 0) { total = "0.00"; } if ($("payment_total")) { $("payment_total").update(parseFloat(total).toFixed(2)); } }, /** * Sets the events for dynamic total calculation * @param {Object} prices */ totalCounter: function(prices){ $H(prices).each(function(pair){ $(pair.key).observe('click', function(){ JotForm.countTotal(prices); }); if ($(pair.value.quantityField)) { $(pair.value.quantityField).observe('change', function(){ $(pair.key).checked = true; JotForm.countTotal(prices); }); } }); }, |