Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to another JSP view as part of the MVC pattern using Slim3 framework on Google AppEngine. I needed to add another button next to the submit button to navigate to a different JSP view. To solve this, I added a new button with the type "button" to the existing form, created a .js file to write JavaScript code for the alternative navigation functionality, and included the .js file in the JSP view. However, despite my efforts, the solution didn't work as expected. Here's the relevant code:

The JSP page containing the form:

...
<body>
    <%@ include file="script.js" %>
    <%@ include file="../header.jsp" %>
    <%@ include file="sidebar.jsp" %> 

    <div id="content">
        <div id="main">
            <p>Hello main admin testimonials edit Index !!!</p>
            <h2><b>Modifica Testimonial</b></h2>
            <form action="update" method="post">
                <h3>Nome: </h3>
                <textarea name="name">${f:h(testimonial.name)}</textarea><br />
                <h3>Cognome: </h3>
                <textarea name="surname">${f:h(testimonial.surname)}</textarea><br />
                <h3>Dettagli: </h3>
                <textarea name="details">${f:h(testimonial.details)}</textarea><br />
                <h3>Progetto:</h3>
                <select name="projectKey" selected="${f:h(testimonial.projectRef.key)}">
                    <c:forEach items="${projectsList}" var="project">
                        <option value="${f:h(project.key)}">${f:h(project.name)}</option>
                    </c:forEach>
                </select>
                <br />
                <input type="submit" value="Aggiorna"/>
                <input type="button" value="Elimina" onclick="deleteFunction()"/>
                <input type="hidden" ${f:hidden("key")}/>
            </form>
        </div>
    </div>
</body>
</html>

script.js:

<script type="text/javascript"> 
        function deleteFunction()
        {
            if (confirm('Ask navigation confirm'))
            {
                window.navigate("bla bla new view url");
            }
            else
            {
                return;
            }
        }
</script>

EDIT: I have updated the function name to match the actual implementation from my original code.

Answer №1

Well, the use of <%@ include file="script.js" %> is proving to be effective as it successfully incorporates the code from script.js onto the page. I've made a crucial adjustment by changing the function name from "delete()" to "fdelete()". It appears that using the name "delete" can lead to complications, as evident when I directly wrote JavaScript on the page (a simple alert) and attempted to call it with the "delete()" function name, resulting in the script not executing. The reason behind this issue eludes me, but it indeed exists.

UPDATE: Years later, as I revisit this dilemma after numerous experiences in web development, it has become clear that naming a function "delete" is bound to cause conflicts due to its status as a reserved word in JavaScript!

O mighty JavaScript deity, please absolve me of my past transgressions; I was once youthful and naive :(

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

Enhancing Web Service Calls with Angular 2 - The Power of Chaining

I am currently facing an issue where I need to make multiple web service calls in a sequence, but the problem is that the second call is being made before the .subscribe function of the first call executes. This is causing delays in setting the value of th ...

Ensure that an HTML table row remains fixed on the screen at all times

I'm looking to make a specific row in my HTML table always visible on the screen, either at the bottom if scrolled off or top. The row should scroll normally as part of the table when it's visible on the screen. How can I accomplish this using bo ...

Linking a watcher property to control the opacity value of inline styles

Struggling to connect the opacity of a div with the value of a slider. <div class="container" v-bind:style="opacity">test content</div> Despite my efforts, I can't seem to make the binding work correctly. When I check in the developer to ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

Steps for relocating Express server (using MERN stack) to a subdirectory and functioning on Heroku

In my MERN stack project, I recently had to reorganize the server-related files into their own subdirectory due to issues with ESLINT, VSCODE, and package.json configurations that were causing errors. However, after making this change, Heroku started thro ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

The series in angular-chart is not displayed at the top as shown in the documentation

angular-chart.js provides an example of a bar chart, which can be found here. Using this as a foundation, I made some modifications to the js and markup code like so. HTML <body ng-app="app"> <div class="row"> <div class="col-m ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

Guide on separating a variable by commas using jQuery

After making an Ajax call to a Java servlet, I am retrieving data and storing it in the 'data' variable upon success. Here is the code snippet: var s1=""; var ticks =""; $('#view').click(function(evt ...

Leveraging the Spread Operator in Redux mapDispatchToProps with SweetAlert2

When I add the swal action creators to the mapDispatchToProps function like this: function mapDispatchToProps(dispatch) { return { getAnimal: (_id) => dispatch(getAnimal(_id)), ...swal } } The issue aris ...

WebRTC functions effectively within the same network, but encounters difficulty when communicating between different IP addresses

Please find my code on Github: https://github.com/rashadrussell/webrtc_experiment/blob/master/public/script.js I am currently working on developing a 1-to-1 video conferencing script using WebRTC. The script is hosted on AppFog, a cloud hosting platform. ...

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

How do I use NodeJS and MongoDB to dynamically populate my webpage with data from a database?

I am working on a small express + ejs application that stores data for registered users. Each user is assigned a "role" that is stored in the database. I would like to display each user's information in an html div, with the div's color refle ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Pass information from one .jsp file to a JavaScript function in another .jsp file

Here is the content of OneEmployee.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <form> <td> <c:out value="${emp.getEmpid()}"/></td> <td> <input type="text" id="fname" value="<c:out v ...

Utilizing Flask for analyzing characteristics of text presented in JavaScript

My current variables consist of: myfruits = ['Apple', 'Banana', 'Lemon'] havefruit = [True, True, False] If the user input changes the values in havefruit, I need to implement JavaScript in my HTML file to display the entrie ...