Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a scriptlet variable into onclick() function call to javascript

Tags:

javascript

jsp

I need to read a variable and then have to pass that as an argument to a function after onclick(). I am using JSP, so I am reading the variable using scriptlets

<% int lateRegDays = 6;%>

I am passing the variable as

onclick="displayDatePicker('startTestAdminNo','mdy',<%=lateRegdays %>,120,0,3);"

But, I am unable to pass the valueof 6. The string "<%=lateRegDays%>" is being passed to the function. However, when I tried to print the value using alert, it worked. The changes I did is,

onclick='<%="alert("+lateRegDays+")"%>'

In the similar fashion, I need to know, how to pass all my arguments to function with this scriptlet variable. The entire code snippet is:

<td><input name="startTestAdminNo"></td>
  <td>
        <chtml:img srcKey="order.calendar.search" onclick="displayDatePicker('startTestAdminNo','mdy',<%=lateRegdays %>,120,0,3);"
            altKey="order.calendar.alt_search" bundle="prompt" />
  </td>

I need help with this as I am stuckand I don't know how to pass multiple arguments along with a scriptlet variable

like image 890
Vamsi K.N Avatar asked Nov 27 '25 17:11

Vamsi K.N


1 Answers

Scriplets will generate the HTML content when the Browser loads the JSP page, so if you want to use it inside your javascript, you need to capture that lateRegDays variable during the page loading time as below:

<script>
var lateRegDays; <!-- global variable -->
function init() {
lateRegDays = '<%= lateRegDays %>';
}
function  displayDatePicker(...) {
  // Get the lateRegDays var
}
</script>
<body onload="init()">
<!-- your code -->
</body>

P.S.: Scriplets are legacy code (invented in early 2000 by Sun), which is not a best practice to use them, so avoid them by using the latest front-end technology stack for the presentation layer.

like image 87
developer Avatar answered Nov 30 '25 08:11

developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!