utilizing spring mvc conditions to dynamically populate parameters in a javascript URL function

In my Spring MVC application, I have implemented a JavaScript calendar control that redirects the user to a detail page for a selected date. However, I am facing an issue where I need to include additional parameters in the URL along with the date. How can I modify the JavaScript functionality to add these parameters when necessary?

Below is the JavaScript code snippet that currently generates the URL with only the date parameter:

        <script type="text/javascript">
                    $(document).ready(function() {
                        $("#dayPicker").datepicker({
                            firstDay: 1,
                            dateFormat: "yy-mm-dd",
                            defaultDate: new Date(${calendar.dayMillis}),
                            onSelect: function(dateText, instance) {
                                window.location = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);
                                }
                        });
                    });
        </script>  

For reference, here's a section of code from the JSP that demonstrates how to generate a URL with additional parameters (pid and eid) if they are not null:

            <c:url var="previousLink" value="/calendar">
                <c:param name="day" value="${calendar.previousDay}" />
                <c:choose>
                    <c:when test="${pid!=null}">
                        <c:param name="pid" value="${pid}" />
                    </c:when>
                    <c:otherwise></c:otherwise>
                </c:choose>
                <c:choose>
                    <c:when test="${eid!=null}">
                        <c:param name="eid" value="${eid}"></c:param>
                    </c:when>
                    <c:otherwise>
                    </c:otherwise>
                </c:choose>
            </c:url>
            <a href="${previousLink}">Previous</a>  

How can I adjust the JavaScript above to include the pid and eid parameters in the URL only if they are not null?

Answer №1

To achieve this, simply combine the URL parameters with the & symbol in between:

let link = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);

if (pid) {
    link += "&pid=" + encodeURIComponent(pid);
}

if (eid) {
    link += "&eid=" + encodeURIComponent(eid);
}

window.location = link;

Answer №2

Upon reviewing your remarks regarding pid and eid not functioning as expected, it appears that adding jquery brackets may be necessary to retrieve the pid and eid values. The updated code snippet would look like this:

var url = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);

if (${pid!=null}) {
    url += "&pid=" + encodeURIComponent(${pid});
}

if (${eid!=null}) {
    url += "&eid=" + encodeURIComponent(${eid});
}

window.location = url;

In addition, if the eid or pid are not actually being added to the model when they are 'null', they may not be considered null in the code. To ensure the desired functionality, you can handle it as follows:

var url = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);

if (${! empty pid}) {
    url += "&pid=" + encodeURIComponent(${pid});
}

if (${! empty eid}) {
    url += "&eid=" + encodeURIComponent(${eid});
}

window.location = url;

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

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

How to use jQuery to extract a JSON snippet from a lengthy string

I received an AJAX response in the form of a lengthy string, which includes HTML and JSON data. The JSON object is embedded within the string and not always at the end. My goal is to extract the JSON object from the string so that I can utilize it with th ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

Problems encountered with React Image Magnifiers while attempting to zoom in with Next.js

When I try to use the react-image-magnifiers plugin to make an image zoom in on hover, it works fine without next.js. However, when I integrate it with next.js, the zoom functionality does not work. Could there be an issue in my next.config.js file? This ...

What might be causing certain ajax buttons to malfunction?

There are 5 buttons displayed here and they are all functioning correctly. <button type="submit" id="submit_button1">Img1</button> <button type="submit" id="submit_button2">Img2</button> <button type="submit" id="submit_button3" ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

What is the method for combining two SC.RecordArray instances in Sproutcore?

Below is the code snippet : queryTree = SC.Query.local('Tree.Category', "categoryId = {categoryId}", { categoryId: this.get('guid'), orderBy: "name ASC" }); queryNote = SC.Query.l ...

Transforming a JSON string into an Object with a field that can accommodate two distinct structures

I am facing the challenge of utilizing the Jackson library to parse a JSON object that contains a specific field "baz" with two different structures. It could either be structured like this: { "foo": "...", "bar": "...", "baz": { "bazAttribute1" ...

Creating a Morphia query targeting specific properties within a Java Collection's elements

I'm having trouble querying a MongoDB document based on field values within an embedded Java Collection. Here is the entity I am working with: @Entity public class StationHistoryEntry // extends ... { @Embedded private Set<SongFeedback> ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

What exactly constitutes a MIDI soundbank?

I'm new to the world of MIDI. Does a MIDI soundbank contain the necessary "instructions" for a MIDI synthesizer to convert into PCM audio? Currently, I have several audio files of varying lengths in PCM format that I want to sequence and provide play ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

What is the reason for placing a ReactJS component, defined as a function, within tags when using the ReactDom.render() method?

As someone who is brand new to ReactJS and JavaScript, I am struggling to grasp the syntax. The component I have created is very basic: import React from 'react' import ReactDom from 'react-dom' function Greetings() { return <h1&g ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

Populate an HTML layout with MySQL information and dynamically add the content to the page using JavaScript

I'm facing a challenge with creating an about us page for a website. I am using a template to structure the page and I want to populate it with MySQL data. I have enclosed the entire <div> of the personcard within a <script> tag, but the p ...

Achieve precise alignment of one view on top of another using the view.animate() method

I am trying to use the view.animate() method to move one view in place of another. Here is the situation: My current layout looks like this: Initial layout (screenshot) When a user taps/clicks on the red image, I want it to be animated and moved exac ...

Tips for overcoming the Chrome Extension Error related to the "script-source 'self'" issue

I've been developing a Chrome extension that uses goo.gl to shorten URLs. Here is the code I'm currently working with: $("#ajaxfiller").text(""); //Retrieve entered URL var longUrl = $("#input2").val(); longUrl = '"' + longUrl + &a ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...