The Split() function in Javascript does not yield any output

Hello everyone, I am new to working with Java script and could use some guidance. My goal is to create a script that adds a user-selected number of days to a date and returns the result. Currently, the script is functioning properly and storing the value in the variable expDate, however, it is in a long format such as "Wed Jan 02 2013 00:00:00 GMT+0800 (HKT)". When I attempt to split this value into different sections using the split function, my output becomes blank.

Any assistance or suggestions would be highly appreciated!

Javascript

<script type="text/javascript">
function setExpDate(){

var formDate = document.getElementById('startDate').value;
var number = +document.getElementById('days').value;


var interval = number;

var startDate = new Date(Date.parse(formDate));

var expDate = startDate;
expDate.setDate(startDate.getDate() + interval);



var splitDate = expDate.split(' ');

var monthFomatted  = splitDate[1];
var dayFomatted  = splitDate[2];
var yearFomatted  = splitDate[3];


document.getElementById('total').innerHTML = monthFormatted;
document.getElementById('daysdays').innerHTML = Dateformatted;
};
</script>
</head>

HTML

<body>

<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">

<select name="days" id="days" onchange="setExpDate(this.value)">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
</select>

 <div id="total"></div> <br/><div id="daysdays"></div>
</body>
 </html>

Answer №1

.split() is typically used to manipulate strings, however, in this scenario, it is being applied to a Date object.

A more appropriate solution would involve the following:

var monthFormatted = expDate.getMonth();
var dayFormatted = expDate.getDay();
var yearFormatted = expDate.getYear();

The methods getMonth(), getDay(), and getYear() are specifically designed for use with Date objects.

UPDATE

It's worth noting that you have defined monthFomatted but then referenced it as monthFormatted.

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

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

What is the best way to include a post identifier in my ajax request?

Currently, I am looking to enhance my ajax functionality by including a post identifier. At the moment, I identify my posts by checking for the presence of a specific input field. Below is the snippet of code that illustrates this: <input name="id" id= ...

Combining two rows into a single cell using AG-GRID

Currently, I am utilizing AG-GRID for angular in my code. Within this grid, I have two columns available - Account.Name and Account.Surname. My goal is to display the values from these two columns within a single cell. To achieve this, I attempted the meth ...

What could be the reason for my jQuery files not being loaded?

I have included jQuery and Bootstrap in my header as follows: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" href="https://maxcdn.b ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

How to rotate a SVG transformation matrix around its center point

CSS .square { background-color: green; height: 40px; width: 40px; } JS var square = { sizeReal : { "width": 40, "height": 40 } , position : { "x": 100, "y": 100 } }; $(". ...

Discover how to extract the value from the server side during document.ready using jQuery without the need for any specific event

In my project, I'm facing a requirement where I need to fetch a value from server-side code using any event and utilize it to create a dialog box. Initially, I attempted to retrieve the value in window.onload but discovered that window.onload is trigg ...

What is the best way to reset everything back to its original position by clicking anywhere on the screen except for the specified div?

Is there a way to make the entire screen reset to its original state with just one click anywhere on the screen, rather than having to click a specific button? Any assistance on this matter would be greatly appreciated. Thank you! JQUERY CODE $(".readNow ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Summarize the array of objects and find the average value for each distinct object name

I'm facing a challenge with an array structure: const originalArray = [ { name: "a", value: 1 }, { name: "a", value: 2 }, { name: "a", value: 3 }, { name: "b", ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Obtain the session value in React

Currently, I am working on a React app along with a server-side application. I have successfully created a user session on the server side and now I want to retrieve its value in my React app. Can someone guide me on how to achieve this? const [user,setUse ...

Identify the moment when a file is being uploaded in a web browser

Could someone guide me on how to use javascript/jQuery to determine if a file is being uploaded by the browser? If not, what is the typical approach for this? Or can I only detect if I am using my custom file uploader and not the browser's? Edit: I ...

Exploring the dynamics of state manipulation in React

In managing a state, I have established a pricing system for coffee for employees when a radio button is selected. const [coffee, setCoffee] = useState(0); const [checkedCoffee, setCheckedCoffee] = useState(true); This is how the new state is being co ...

Firebase issue: The function ref.once is throwing an Uncaught TypeError and is not recognized

I am attempting to utilize Firebase for both uploading a file and storing it in my database simultaneously. I want to track the number of uploads so that I can rename each file uniquely. While I have successfully uploaded and stored a copy in the database, ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

Is JSON Compatible with the Switch Statement?

Could someone help me with creating a switch statement in JSON? {"Errors":{"key1":"afkafk"},"IsValid":false,"SuccessMessage":""} I attempted to use: switch(response) { case response.Errors.key1: alert('test'); default: } However, t ...