JavaScript Age Calculator - Counting Days

Hey there! I've got an interesting problem. I currently have three text boxes on my webpage, and what I want to achieve is having a fourth text box generated when the user clicks a button. The content of this new text box should be filled with the data from the other three boxes. So far, I've been successful in accomplishing this using the following code:

<html>
   <head></head>
   <body>
      <script>
         function addTextBox() {
         var element = document.createElement("input");

         element.setAttribute("type", "text");
         element.setAttribute("id", "Text4");
         document.body.appendChild(element);

         fill();
         }

         function fill() {
         input = document.getElementById("Text1").value + " " + document.getElementById("Text2").value + " is " + document.getElementById("Text3").value;;;
         document.getElementById('Text4').value = input;
         }

      </script>
      <form>
         <input type="text" id="Text1" value="Firstname">
         <input type="text" id="Text2" value="Lastname">
         <input type="text" id="Text3" value="Age">
         <input type="button" onclick="addTextBox()">
      </form>
   </body>
</html>

But here's where I need assistance - I want to take the age entered by the user in the third textbox and convert it to their age in days before displaying it in the fourth box. Can anyone provide guidance on how to achieve this?

Answer №1

Here is a simple function that can help you calculate the number of days based on an age passed as a parameter:

 function calculateDaysFromAge(age)
    {
    var currentDate = new Date();
    var startDate = new Date();
    startDate.setFullYear((currentDate.getFullYear() - age));
    var difference = currentDate - startDate;
    var oneDayInMilliseconds = 1000 * 60 * 60 * 24;
    var totalDays = Math.floor(difference / oneDayInMilliseconds);
    return totalDays;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Is there a way to search for the keyword "/test/" within a lengthy string using Regular Expressions?

When faced with a string structured like this: const myString = /example/category/modify?itemID=someID&type=number How can I efficiently extract the segment "/category/" by employing: const subSegment = myString.match(...); My framework of choice i ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Measuring Time Passed with JavaScript

I've been working on a small piece of code that needs to achieve three tasks: User should input their birthday User must be able to view the current date When the user clicks a button, they should see the time elapsed between their birthday and the ...

Vue .filter doesn't work with reactive data sources

I'm currently working on a project that involves creating a dynamic shipping estimate in a Shopping Cart. The challenge I face is retrieving shipping methods from an API endpoint and making the data reactive to update in real-time based on the selecte ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Tips for securing firebase-admin credentials in Next Js

I've encountered a challenge while using firebase-admin in Next Js. I attempted to hide the firebase service account keys using environment variables, but ran into an issue because they are not defined in server-side on Next JS. As a workaround, I had ...

Implementing JavaScript if statements that evaluate to true without cycling through all my if statements

Hey everyone, I've encountered an issue with my code. When testing each part individually, everything works fine. However, when all parts are combined and the first IF statement is reached, the form gets submitted without validating the others. Can an ...

Can you please guide me on how I can implement a top AJAX menu like the one on StackOverflow

Have you seen the menu that appears when you first visit a website, with an 'x' on the right to close it? I believe this is done through AJAX - what specific terms should I look up to implement this feature? ...

Unable to bind knockout dropdownlist data during an ajax request

Trying to connect a dropdownlist in knockout with MVC 4. Below is the code snippet: Action public JsonResult GetUserTypes() { using (QuestApplicationEntities db = new QuestApplicationEntities()) { var usertypes = (from ...

Generate summary columns using a provided list of headers

In my dataset, there is survey data along with columns containing demographic information such as age and department, as well as ratings. I want to enhance the dataset by adding new columns based on calculations from the existing rating columns. The goal ...

What is the best way to duplicate a value and save it in an array?

I have a calendar and I want to be able to copy the selected day's value and store it in an array. Then, if another day is clicked, I would like to add the current day's value along with the previous day's value to the array. Users should be ...

Display a message box in the external window just before the close event

I am trying to implement a message box that will appear when the user clicks the (X) button of an Ext window. However, I am facing an issue where the window closes before the message box is shown. Below is the code snippet I have written: var assignReport ...

Display four unique automobile insignias using Webcomponent/Stencil.js

Exploring Web Components and Stencil.js for the first time, I'm currently developing an application that offers detailed car information based on the user's selection of car type. The challenge I'm facing involves displaying four different l ...

Unable to provide feedback on the input elements

ISSUE: Unable to provide input in the input fields // Enable dragging for the DIV element: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementB ...

Jasmine test failing due to uninitialized angular controller

I encountered some difficulties while writing jasmine tests for an AngularJS application that utilizes angular ui-router. Despite proper initialization of my services and app in the test, I found that the controllers were not starting up correctly. In an e ...

Creating a search-enabled multi-select feature in a Tabulator.js column

Currently, I am working on a project involving Tabulator.js and attempting to incorporate a column with a multi-select feature that includes a search option. My approach has been to utilize the Select2 library, but I have run into some challenges. Here is ...

In a foreach loop, ensure that the subsequent input field is mandated

After creating a function to check if my checkbox input field has been checked, I encountered an issue where the required attributes were not being added to the desired input fields. Despite trying different solutions mentioned in this Stack Overflow threa ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...