Executing a JavaScript function with no event

This particular code snippet is taken from a.jsp:

    <script type="text/javascript" >
    function checkDates(date1, date2)
    {
     var x = date1.split('/')
     var y = date2.split('/')
     var firstDate = new Date(x[2],x[0],x[1])
     var secondDate = new Date(y[2],y[0],y[1])
     var difference = (secondDate - firstDate )
     var daysDifference= difference / (1000 * 60 * 60 * 24);
    }
    </script>

    <% String initialDate="2013/07/12";
       String endDate="2013/07/14";%>

   <script>
    var result=checkDates('$initialDate','$endDate');
   </script>

   <body>
   <% String scriptCode="<script>document.writeln(result)</script>";
      out.println("Output value="+scriptCode); %>
   </body>

The objective here is to extract the number of days (as 'daysDifference') between two given dates ('initialDate' and 'endDate') as an output. However, instead of getting the desired calculation, the current output appears as "Output value=NaN". Can anyone assist in identifying the issue with this coding? Appreciate any help.

Answer №1

This particular question proved to be quite challenging to provide a solution for. It seems that the task at hand involves passing variables from a scriptlet to JavaScript using EL. In order to achieve this, it is recommended to:

  • Declare the variable in the scriptlet as either a pageContext attribute or a request attribute, following the instructions provided here: How to evaluate a scriptlet variable in EL?
  • Utilize JSTL <c:out> to transfer the variable from EL to your JavaScript function.
  • In line with GauravSharma's answer suggestion, include a return p; statement at the conclusion of your JavaScript function.

The revised code snippet should resemble the example below (tested on Tomcat 7 and displaying the result "2" in the browser):

<script type="text/javascript">
    function chk(d, e) {
        var x = d.split('/');
        var y = e.split('/');
        var a = new Date(x[0], x[1] - 1, x[2]);
        var b = new Date(y[0], y[1] - 1, y[2]);
        var c = (b - a);
        var p = c / (1000 * 60 * 60 * 24);
        return p;
    }
</script>
<%
    String b = "2013/07/12";
    String c = "2013/07/14";
    pageContext.setAttribute("b", b);
    pageContext.setAttribute("c", c);
%>

<script>
    var myVar = chk('<c:out value="${b}" />', '<c:out value="${c}" />');
</script>

<body>
    <%
        String st = "<script>document.writeln(myVar)</script>";
        out.println("value=" + st);
    %>
</body>

As mentioned in the comment left on your initial question, this scenario serves as a learning exercise for practicing the integration of scriptlets, EL, JSTL, and JavaScript. It is crucial to emphasize that this type of code is not suitable for deployment in a live production environment under any circumstances. The usage of scriptlets has been discouraged for an extended period. For further details, please refer to: How to avoid Java code in JSP files?. Additionally, it would be beneficial to discuss this with your instructor, professor, or tutor responsible for instructing you on Java web development practices.

Answer №2

Make sure to include return p; at the end of your function.
It is important to return a value from your function in order to avoid displaying undefined.

function calculateDaysDifference(startDate, endDate)
{

 var x = startDate.split('/')
 var y = endDate.split('/')
 var a = new Date(x[2],x[0],x[1])
 var b = new Date(y[2],y[0],y[1])
 var c = ( b - a )
 var p= c / (1000 * 60 * 60 * 24);
 return p;
}

Answer №3

Just use the following code snippet:

var myVariable = check('$b', '$c');

Make sure to call this on document ready.

The reason for this is because JSP has just injected the script into the document, but it has not been executed yet.

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

Using Selenium Webdriver to initiate the play function of a video by clicking on the control

Is there a way to play the video on this page by clicking the play button? I noticed a 'playpause' control in the JavaScript, but I'm unsure how to activate it. <div id="videoModal" class="reveal-modal expand open" style="display: block ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

How can a Spinner be incorporated into a Button within a Modal while running in the background?

I'm attempting a rather simple task, but I'm encountering difficulties. The issue I'm facing involves a modal that prompts the user for confirmation. Once the user clicks "confirm," a URL is fetched, triggering a background process. During ...

How can I retrieve the identical fingerprint used by AWS from x.509 using node-forge?

Is there a way to obtain the certificate ID / fingerprint of an x.509 certificate using the node-forge library? Update I am trying to configure AWS IoT and believe that AWS uses a specific fingerprint algorithm to generate the certificate ID. This inform ...

Create a 3D visual display with the use of three.js in Javascript

I'm navigating my second round with three.js and have been experimenting for a good 3 hours. However, I seem to be at a loss when it comes to determining my next steps. My goal is to create something similar to the layout found here: I've manag ...

Incorporate a SharpSpring form within a custom React component

Trying to integrate a Sharpspring form script into my React component (page.jsx). The form needs to be placed outside the <head></head> element and inside the <div> where I want to display it. The original HTML code for embedding the for ...

Error message: Django error 404 - page not found, issue with AJAX request

Looking to make an ajax request to a Django server and receive a response with random data. The homepage is functioning correctly, but when the ajax request is made, a 404 error is returned: Using the URLconf defined in bms_project.urls, Django tried the ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

executing functions that return a JSX component within the render method

In an effort to enhance readability, I am striving to condense the length of the render() method by utilizing class methods that contain isolated JSX elements. A snag arises when attempting to apply this technique to more than one JSX element. Despite en ...

Checkbox search column in jQuery DataTables

I have implemented jQuery DataTables Individual Column Searching on a table where one of the columns contains checkboxes. HTML Structure <table id="NewTable" class="table table-bordered table-striped"> <thead> <tr> ...

Exploring Redis: Customizing conversion configurations

When working with spring-data-redis in a Spring Boot application, how can we configure custom converters that are auto-wired or injected? I came across the @ReadingConverter and @WritingConverter annotations in the spring data redis documentation. However ...

Encountering an issue with Discord JS that says "unable to access property 'content' because it is undefined"

CODE IS BELOW I have recently created a discord bot and included a message file within the events--guild directory. module.exports = (Discord, client, message) => { const prefix = '!'; if(!message.content.startsWith(prefix) || mess ...

Double-click the link to trigger the activation of the state using ui router

The schoolyears state is initially active. Whenever I attempt to activate the schoolyears.create state by clicking a button, I find that I need to perform this action TWICE for the create schoolyear view to be rendered. What am I doing incorrectly? INDEX ...

I encountered an issue where vue-toastr fails to function properly within an inertia.js environment

While working on a page with Inertia.js, I encountered an issue when trying to integrate vue-toastr into my Vue template file. Unfortunately, it doesn't seem to be functioning as expected and I'm unsure of how to resolve this issue. Any suggestio ...

Can the start and stop times of the typed.js plugin be controlled for typing text?

The typed.js jQuery plugin creates the illusion of text being automatically typed on screen by a robot. Despite researching the resources related to this plugin, I have not come across any information on how to control the starting and stopping of the typi ...

Is it necessary to convert an HTMLCollection or a Nodelist into an Array in order to create an array of nodes?

Here we go again with the beginner guy. I'm working on this exercise from a book called "Eloquent JavaScript". The goal is to create a function similar to "getElementByTagName". However, the first function below is not returning anything and the secon ...

Mouse over the image link and update the CSS text effect

I need help with a WordPress plugin and I'm trying to avoid making too many changes to the HTML output. Is there a way to make both the image and text change color when hovered over? You can see what I'm working on here - http://jsfiddle.net/3JE ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Are there any security concerns involved in creating a game using a combination of JavaScript, Electron, and Three.js?

I'm not looking to create anything on the scale of an MMORPG, just a small game similar to Faster Than Light. Is there a way to protect against cheat engine or prevent users from running their own JavaScript in the game, considering anyone can access ...