views:

101

answers:

3

I have the following function call inside a jsp page.

jQuery(function($){
   $("#product").mask("99/99/9999",{placeholder:" "});
});

What I want to do is pass a different string into the .mask function. In pseudo code it would look something along the lines of:

String passedParam= someString  
if(test):
  passedParam = "someotherString"

jQuery(function($){
   $("#product").mask(passedParam,{placeholder:" "});
});

Being new to both jsp and javascript I do not know the correct way to translate this pseudo code into actual working code.

A: 

Well in my jsp I would do something like this:

<%
String mask = someString  
if(test):
  mask = "someotherString"
%>

jQuery(function($){
   $("#product").mask(<%= mask %>,{placeholder:" "});
});
ryan
That's also a way, but that's pretty old fashioned. The use of scriptlets is [discouraged](http://stackoverflow.com/questions/3177733/howto-avoid-java-code-in-jsp-files) since over a decade. Use taglibs/EL whenever possible ;)
BalusC
+1  A: 

You can use taglibs/EL in JSP to print a string as if it's JavaScript code. You know, JSP runs at webserver machine, produces HTML/CSS/JS and sends it to the webbrowser which in turn starts to run JS code. You should write server side code accordingly that its HTML/CSS/JS output looks right when you're doing View Source in webbrowser.

Your pseudocode is a bit ambiguous, but I bet that you're looking for something like this:

jQuery(function($){
   $("#product").mask('${test ? 'someotherString' : mask}',{placeholder:" "});
});

(don't pay attention to syntax highlighting, the code is correct, the highlighter doesn't recognize EL)

The ${} thing is EL (Expression Language). It will be processed when JSP runs. It should work in template text as per Servlet 2.4/JSP 2.0 (which is already over 5 years old). The ?: is the well known conditional operator. If the expression evaluates true, then the part after ? will be assigned/printed (in this case the literal string "someotherString"), otherwise the part after the : (in this case the scoped variable mask).

This will end up in the webbrowser as

jQuery(function($){
   $("#product").mask('someotherString',{placeholder:" "});
});

or

jQuery(function($){
   $("#product").mask('someString',{placeholder:" "});
});

depending on the boolean outcome of test.

BalusC
perfect! Thank You!
Soldier.moth
You're welcome :)
BalusC
A: 

Handle the mask variable using JSP, then put it inside jQuery code.

<%
   String mask = "";
   if (test) {
       mask = "something";
   }
   else {
       mask = "something else";
   }
%>

jQuery(function($){
   $("#product").mask('<%=mask%>',{placeholder:" "});
});
Impiastro