Is there a way to incorporate Java variables into a JavaScript function on a JSP page?

I've put together a JSP page:

<%
int num1 = 10;
int num2 = 20;
%>

<script>
function display(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');    
              data.addColumn('number', 'Number');
              data.addRows([
                ['category1', <%= num1 %>], ['category2', <%= num2 %>]]);
}
</script>

An issue arises when trying to use these variables within the JavaScript function.

"num1" cannot be recognized as a variable.

"num2" cannot be identified as a variable.

Answer №1

To correctly format the data, you can utilize either double or single quotes:

data.addRows([['category1', "<%= value1 %>"], ['category2', "<%= value2 %>"]]);

If preferred, single quotes can be used as follows:

data.addRows([['category1', '<%= value1 %>'], ['category2', '<%= value2 %>']]);

Answer №2

To display your variable, you can follow this format:

"<%=var1%>"

It is recommended to avoid using scriptlets. Instead, consider utilizing a method like jstl. Here's an example:

<c:set name="var1" value="10" />    
<c:set name="var2" value="20" />

Now assign them like this:

var value1 = "${var1}";
var value2 = "${var2}";

You can incorporate them into your function like so:

data.addRows([['cat1', "${var1}"], ['cat2', "${var2}"]]);

If you'd like to learn more about the differences between JSTL and Scriplets, check out this informative article:

Comparing JSTL and JSP Scriptlet Programming

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

Issue with submitting form using q-select

After incorporating a q-select element into my form, I noticed that the submit event is not triggering. Strangely, when I remove the q-select element, the submit event works as expected. <q-form @submit.prevent="addNewRole" class="q ...

Angular: Issue encountered while attempting to differentiate an '[object Object]'. Arrays and iterables are the only permissible types for this operation

I encountered the following error message while attempting to retrieve updated data: Error trying to diff '[object Object]'. Only arrays and iterables are allowed Snippet of Get Code: allDatas allData(data) { this.allDatas = data } Up ...

The useEffect hook is activated whenever any function within the component is executed

After extensive research, I have not been able to find a solution to my question. Any help would be greatly appreciated. This code snippet represents a functional component that deals with state and props: // blog id const { id } = props.match.params; // ...

Is it possible to interact with hidden elements in Selenium using Java WebDriver without the need for the javascript executor?

Is there a way to interact with hidden or non-visible elements using the Java Selenium Webdriver without relying on the JavaScript executor to simulate clicks? I need to run tests on a browser that has JavaScript disabled, so the traditional jse method w ...

What is the best way to conceal an image generated by a control - using JavaScript, CSS, or another method?

I am looking to remove the background image of the ReportView control, specifically the toolbar_bk.png image. Rather than hiding it, I want to set it to none. How can I achieve this easily? Should I use server-side code, CSS, JavaScript, or perhaps jQuery ...

Selecting options in table is disrupted by filtering in ng-repeat

My table showcases selectable information, featuring parent rows and child rows. I am seeking a solution where only the parent rows are selectable if they have no children; otherwise, only the child rows should be clickable. Essentially, it's a selec ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Tips on efficiently locating WebElements through their attributes, excluding common ones such as "class" and "name" - for instance, "title"

Being new to Java and Selenium, I apologize if my question seems basic. Currently, I am using the following code: driverChrome.findElements(By.className("blabla")); This code helps me find elements with "blabla" as their className. For example: <spa ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

Managing redirects in CodeIgniter 3

I have encountered an issue while using Codeigniter 3. When I submit a form, the validate function name appears in the URL before being redirected to another page. How can I hide the validate function name in the URL during submission? Here's a sampl ...

Best way to update a series of IDs with various names using the map function in JavaScript

I currently have a collection of 10 "tags", each with a unique ID format (00:00:00:xx:xx:xx) and translatedID format (TXT). I receive strings containing violating tags that I need to convert from translatedID to ID. Below is the map of values: Map(10) { ...

Is there a way for me to locate and access the web element associated with the "Canvas Id" on an HTML page?

Currently, I am utilizing selenium3 webdriver to automate an html page that contains numerous click buttons. However, I am encountering difficulty accessing these buttons as the entire page is displayed as a canvas element. At this point, I am stuck and wo ...

Unlocking the secrets of input type conversion

I am developing a timer application where users can set the time in the format "mm:ss" (minutes:seconds). However, my app crashes because it does not accept colons in the input. How can I convert the input type from "mm:ss" to "mmss" without changing the a ...

What is the best way to incorporate a translate, rotate, and scale tool into my threejs environment?

Recently, I experimented with the THREE.js editor tool. When you click on an object, a set of tools for translation, rotation, and scaling appear in the scene. These tools allow you to modify the object's position, rotation, and size. I attempted to u ...

What is the process for integrating ion-tabs with IonicVueRouter within an Ionic (vue.js) application?

My Project Idea I have a vision to create an innovative exercise warm-up application. The app will be divided into two main sections: a workout tab and a settings tab. The user journey will start with selecting a workout plan, then choosing specific exerc ...

Utilizing React to showcase a variety of questions randomly all at once

I am developing a quiz application with an array containing five questions. However, I would like these five questions to be displayed randomly but all at the same time. const shuffleQuestions = (array) => { let shuffled = array[Math.floor(Math.ra ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Having trouble updating a partial view with ajax in MVC Razor after submitting a form from another partial view nested within it

On my website, there is a chat page similar to Facebook's. Initially, I set it up using a basic form submission method that would refresh the entire page whenever a post was made. Now, I am looking to switch to using ajax/jquery so that only my partia ...

My custom function is not invoking the Firebase function createUserWithEmailAndPassword

The function createUserWithEmailAndPassword is not being triggered within the SignUpUser function when the onClick event occurs. However, it works when I use onClick={signUpUser(email,password)} import React from 'react'; import styled from &apo ...