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

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

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.

Related

Creating a reusable javascript function instead of copy/paste

I made a page I need to have in different instances. In short it is used to fill in different parts of a script and then display said script on the page for the user to copy it.
This script below handles the main part of the job, getting a field from HTML and then i can call the result in html to be displayed.
var urlField = document.getElementById('urlField').value;
var resultUrl = document.getElementById('resultUrl');
resultUrl.textContent = urlField;
Problem: there are different fields, eg. url, startdate, enddate, adschedule, etc. so I would like to have a reusable script that just says get the respective field and result the value which is assigned to it in html.
Can I do this somehow? I was researching the function "this" in javascript, but it is too complicated for my current knowledge. Bear in mind that I am in only a very basic level.
You can find the whole codepen to understand the issue better here: https://codepen.io/kmb5/pen/GxZbZq
Add parameters to your re-usable function and then call it whenever you need to use it. Use javascript to get the required data and pass it in as parameters.
reusable.js:
function myFuncWithParameters(parm1, parm2, parm3){
}
Alternatively:
function myFuncWithParameters(myObject){
//access properties from the object: myObject.parm1, myObject.parm2, myObject.parm3
}
Using the object route might make it easier since the order of the properties will not matter like parameters. Regardless of either method you will have to validate the input.
In your html pages, you will need some More JavaScript and HTML to bring in the JS and call it.
<html>
<head>
<title>my page</title>
<script scr="path to reusable js"></script>
<script src="path to this path's js"></script>
</head>
<body>
my page
</body>
</html>
If you look at the script tags, by importing the reusable js you can use it in javascript that was written / imported further down into the page.
In order to ensure you have access to an imported function, you can check if the function you need is defined:
if(typeof(myFuncWithParameters) !== 'undefined' && typeof(myFuncWithParameters) == typeof(Function){
//myFuncWithParameters will definitely be defined and is a function, if we get in here
}else{
//myFuncWithParameters is not defined and/or is not a function
}
In your html page to call the re-usable function...
var parm1 = value;
var parm2 = value;
var parm3 = value;
myFuncWithParameters(parm1, parm2, parm3);
In you decide to use the object:
var myObject = {
'parm1' : 4,
'parm2' : 6
}
//myObject.parm1 == 4
myFuncWithParameters(myObject);

How to access a variable among multiple javascript files

Currently i have 2 html pages and 2 java script pages,say
h1.html,h2.html
j1.js,j2.js
where can i declare a variable so that the variable can be accessible between both of java script and html files
i want to initialize a value to that variable in first java script file and access that value in the second java script file
if you want to access variable values across two html files even after the page loads you can use localStorage in js.
say if you want to set a value for a variable localStorage.setItem("newvariable", 'variablevalue'); and for getting value use this var getValue = localStorage.getItem("newvariable");
EDIT:
for your base question refer those js files one by one
<script src="j1.js"></script>
<script src="j2.js"></script>
you can declare the variable in any javascript file, and just include the file next to the other javascript file forexample.
// for example if you have file1.js like this.
var myvalue = 25;
You can then save this file and include it in your main or other html files for example at the bottom of your html document.
<html>
<body> </body>
<script src='file1.js'></script> // put the javascript file with your variable declaration on top of the other file you want to access the value from.
<script src='file2.js'></script>
</html>
after the above you can then just print the variable in 'file2.js' like this.
// inside file2.js
console.log(myvalue) // which was declared in the 'file1.js'
hope this helps.
You can bring your javascripts in to the <head> of your html then you can refer to the javascript as a function passing values as a parameter and returning data as well.
PS Don't forget to declare the javascript on your form.

Is there a way to send variables to javascript files?

is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>

Grails 2.0: Use Service in javascript function in GSP

I am just wondering how I can call a method of a service from within a function within a GSP. I tried the following but it does not seem to work:
<%# page import="com.company.MyService" %>
<%
def myService =grailsApplication.classLoader.loadClass('com.company.MyService').newInstance()
%>
<html>
<head>
[...]
<script language="javascript">
function myFunction() {
if (${myservice.isSomethingAvailable()}) {
[...]
}
}
</script>
I am pretty new to javascript and Grails. Not sure how to achieve that or if it's even possible. Any help appreciated.
Thanks a lot
Jonas
loadClass().newInstance() creates new instance of object, not spring bean (i mean it's not tied to grails infrastructure), i'm sure it's not what you want
You can pass service from your controller, like render(model: [myService: myService]) (you have to declare it at controller lever)
It's much more correct way is to pass result of this call, not service itself. I mean: render(model: [isSomethingAvailable: myService.isSomethingAvailable]) and test it as if ($(isSomethingAvailable)) {
Notice that gsp is processed in server-side, not client-size. So it doesn't matter where you use your variable - on javascript code, or html code. And also, you can use gsp if tag: <g:if test="${isSomethingAvailable}"> instead of preparing javascript to check value on client-side (because you already know the result)

passing a parameter using JSP include directive

I need to pass a parameter to a page using JSP include directive find my code below:
<script>
var gTIID
function showPlayerList(pTIID)
{
gTIID=pTIID;
$("#IdtournamentMessageMain").hide();
$("#userListFrame").show();
}
</script>
<%# include file="players_list.jsp" %>
How can I pass gTIID to players_list.jsp in the players_list.jsp page gTTID is named tiID (/player_list.htm?tiID=gTIID) ?
Thanks in advance!
since you are using the <include> directive, gTIID should already be available.
Alternately, you could set them in one of the scopes (request, session, application) and then fetch from the same scope in your other JSP.
Or, you could also use <jsp:include> and <jsp:param> to achieve this.
You'll be able to acces gTIID in players_list.jsp. There's no need to pass it as a parameter, as it's a global-scope defined variable. However, take into account that the variable is only defined and initialized in the including page, not players.jsp. If that page is referenced somewhere else, it may be undeclared.
I solved the issue using an hidden input box(id="tidhide") in the "players_list.jsp page initialized to -1 and I set it in the showplayer function, find my snippet code below:
Parent page:
function showPlayerList(pTIID)
{
gTIID=pTIID;
$("#IdtournamentMessageMain").hide();
$("#tidhide").val(pTIID);
oTable.fnDraw();
$("#userListFrame").show();
}
bye!

Categories

Resources