What is the best way to transfer a map from Java to JavaScript?

I have a dropdown menu with an information tooltip icon next to it. When the user changes the selection in the dropdown and hovers over the info icon, a description for the selected item should appear as shown in the image:

https://i.sstatic.net/K1S64.jpg

Currently, I have a backend map of values where the key is the dropdown value and the value is the corresponding description. I want this map to be accessible in the frontend (JavaScript). There are several options available:

1- Make an AJAX call on each value change (inefficient due to unnecessary calls to the backend)

2- Pass the map as a JSON object to a hidden HTML element and retrieve it from there (complicated by escaping characters in JSON)

3- Use data attributes, but my framework does not support HTML5

4- Fetch the JSON via AJAX after page load and store it in a JavaScript variable (wasteful use of server resources)

5- Create a global variable in my JSP using declaration tags (not thread-safe and involves scriplets)

I opted for the fifth solution since the map is static and concurrency is not a major issue. Additionally, the framework I'm working with heavily relies on scriplets.

Does anyone have any other recommendations based on the solutions mentioned, or possibly offer alternative solutions?

Answer №1

One way to handle this issue is by passing the map as a JSON object to a hidden HTML element and then retrieving it, although dealing with the escaping of quotes and other characters in JSON can be problematic.

To simplify this process, you can utilize JSON.stringify() and JSON.parse().

I recommend using this method - stringify the JSON object, place it in an element, and then parse the data when needed.

var obj = {foo: 'bar', arr: ['baz','foobar']};

var el = document.getElementById('jsonData');

// Set the value here -- this would typically be done in your JSP template
el.setAttribute('data-json', JSON.stringify(obj));

console.log(JSON.parse(el.getAttribute('data-json')));
<div style="display:none" id="jsonData"></div>

Answer №2

Here is my strategy.

  1. Create duplicate DOM elements for each choice, initially kept hidden.
  2. Upon triggering the Onchange event of the select box or hovering over the tooltip icon, process the message and reveal it.

When dealing with a JSP loop, you have two options to consider: leveraging the value and index of the select box.

1. Utilize the value field of the combobox (dropdown list/HTML select) as: ${c.id}

2. Use the loop index as: ${cStatus.index}

<c:forEach items="${somethingList}" var="c" varStatus="cStatus">        
    <input type="hidden" id="hiddenToolTip${${cStatus.index}" value="you have selected XXX. XXX is blah blah blah">
 </c:forEach>

Subsequently, in the mouseover event of the tooltip function:

You can retrieve the currently selected option's index or value, fetch the corresponding data from the hidden field, and display the tooltip.

var tooltipText=document.getElementById("hiddenToolTip"+ document.getElementById("comboBoxId").value ).value;
alert("here is tooltip text="+tooltipText); 

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

Contrasting actions when submission occurs by pressing ENTER versus clicking the submit button

Incorporating an HTML form input element that utilizes a SearchBox from the Google Maps Places API for auto-completion is proving to be quite challenging. Within my JavaScript code, I have instantiated a SearchBox as shown below: var input = $('#spot ...

The length of a JSON array is consistently one in AJAX with Codeigniter 4

My goal is to transmit data from my checkbox for deletion to the controller through ajax using my js file. While the data is being passed successfully, I am encountering an issue where the length always shows as 1 when I use count() or array_length(), even ...

Having difficulty entering a date with sendKeys in Selenium WebDriver

When attempting to use Selenium WebDriver's sendKeys method to input a date into a date field, I encountered an issue similar to that of a calendar field. Interestingly, using "type" within the date field worked perfectly with Selenium RC in the past ...

The "checked" property is absent in the ASP.NET checkbox within the gridview

In my asp.net gridview control, the checked property seems to be missing. I am trying to access the checked property using jquery Gridview structure: <Columns> <asp:TemplateField> <ItemTemplate> ...

Obtain the onchange event trigger following a change in select's value using JavaScript

Within my form, users can save their progress. One of the fields in this form is a dynamic SELECT that triggers another SELECT based on the user's choice using the ONCHANGE event. However, I am facing an issue when it comes to loading a saved form. I ...

Can you explain the purpose of "screenSize" attribute in the Android Manifest file?

Hey there, I'm dealing with a situation in my Activity where I have multiple Fragments running AsyncTasks. The issue arises when I change the device orientation while an AsyncTask is still in progress, leading to the app crashing. I came across some a ...

The jQuery spoiler functionality is rather basic and only partly functional

I decided to create a very basic jQuery spoiler feature by using the code below: HTML: <a href="" onclick="return false" class="spoiler" content="spoiled content"> Reveal spoiler </a> jQuery / Javascript: $('a.spoiler').cli ...

Navigate to a specific location on the webpage without modifying the current URL

When a page is loaded, I want it to automatically scroll to the #content section without changing the URL. I attempted to achieve this using the following code: window.location.hash = "content"; window.location.replace("#content", ""); However, the #con ...

Attempting to prevent the insertion of duplicate values more than once

Is there a way to prevent duplicate values from being submitted in my simple site? Currently, I have implemented a function that allows users to input a name and a mark. However, if the same values (name & mark) are entered, I want to notify the user and ...

Obtaining repository data using JGit

I am looking to retrieve statistics about a repository using the Github statistics API which can be found at My question is, can I achieve this by utilizing the JGit library? After browsing through Stack Overflow and Google for information, I have been u ...

Decision on how to exchange data (JSON or traditional method)

In my current project, I am developing a user-friendly application that allows users to design their own web interface using various tools. Users can create drag-and-drop elements and I need to store this data in a database once they finalize their desig ...

An issue arose while trying to create typed transformations from JSON data using a case class

Currently, I am working on creating a strongly typed dataset for the case class Person. Here is the code that I have so far: import org.apache.spark.SparkConf import org.apache.spark.sql.SparkSession import scala.collection.mutable.ArrayBuffer import org. ...

The slideToggle function in jQuery seems to have trouble working on a Joomla platform, however, it functions perfectly on jsbin

I'm currently working on a website and I'm trying to implement the jQuery slideToggle feature to move some blocks. Everything seems to be working fine when I test the code on jsbin.com, but for some reason, it's not functioning properly on m ...

WordPress is failing to deliver a response from AJAX

I have a button in my template that should display 'Next is clicked' when pressed. However, after making a post request I am only seeing the first message and not 'Got response!' in the console. The following code is from my js/inputti ...

Is it possible to validate input only during insertion in Objectionjs without validation during updates?

const BaseModel = require("./base_model.js"); class CustomerModel extends BaseModel { static get tableName() { return "customers"; } static get jsonSchema() { return { type: "object", required: ['na ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

"Extracting key-value pairs from an observable in Angular 2: A step-by-step

Trying to display the key/value pairs from the server in Angular using RxJS. Below is the code snippet: let listener = c.listenFor('addMessage'); listener.subscribe(mesg => { console.log(mesg); }); However, it currently o ...

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

Accessing a JSON file over a network using JavaScript

Struggling to access a basic data file using JavaScript, and it's proving to be quite challenging. The file will be hosted on a remote server and ideally accessed via HTTP. While I'm new to JavaScript, I've come across JSONP as a potential s ...

Encountering an issue while attempting to test geolocation functionality in the web browser

I've been working on integrating the geolocation API into my app and came across a suitable resource at the MDN website. However, when I attempted to test for the existence of the geolocation object in the browser, I encountered this error: Server Err ...