I just need your help about my code. My problem is how can I access smarty variable within jquery or javascript file? Becuase my smarty variable is a URL request from my controller. And I need to use that variable for creating validation. Here's my code.
{$get.search_by} {**works without error**}
{literal}
<script type="text/javascript">
$(document).ready(function(){
var dispatch = "{$get.search_by}"; //can't access
var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04";
var old_class = "it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03";
var toggleState = true;
//could not access
if(dispatch == companies.catalog){
alert("catalog");
}else{
alert("product search");
}
console.log(dispatch);
Try this code
var dispatch = '{/literal}{$get.search_by}{literal}'
To make things cleaner, you can move the {literal} tag down and also escape the $get.search_by variable (in case search_by may have a string with a quote i.e. "let's try"):
<script type="text/javascript">
var dispatch = '{$get.search_by|escape:'javascript'}';
{literal}
Related
I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?
Spring-side:
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("message", "hello");
return "index";
}
Client-side:
<script>
....
var m = ${message}; // not working
alert(m);
...
</script>
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript">
var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
</script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
var message =/*[[${message}]]*/ 'defaultanyvalue';
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[#{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
MAKE sure you have thymleaf on page already
//Use this in java
#Controller
#RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [( brackets which wrap the variable.
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the
URLs embedded in it. Here are the steps (if you are using Spring MVC)
#RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Assuming request attribute named "message":
request.setAttribute("message", "this is my message");
To read it in the html page using Thymeleaf template:
<script>
var message = "[[${message}]]";
alert(message);
</script>
How to use var aid value assign into $data array? I am getting error: "Use of undefined constant aid". I am working on Laravel 5.4. I want to show ($data['services'][aid]->servicesubdetails) value in tage. My code is below:
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html('{{ ($data['services'][aid]->servicesubdetails) }}');
}
</script>
Single quotes are interrupted by another single quote.
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html(“{{ ($data['services'][aid]->servicesubdetails) }}”);
}
</script>
Notice “ instead of ‘.
EDIT
You can use json to use you PHP array in javascript
Look at LaravelDisplayData and PHPJsonEncode
<script language="JavaScript">
var data = #json($data)
function theFunction(e)
{
var aid= e.target.id;
$("p").html(data.services[aid].servicesubdetails);
}
</script>
I am passing div name in the query string from one html page and retrieving that div name on the other html page. Now I want to display that specific div on the page.My code is
function onLoad()
{
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block"; //error is in this line
}
But I am getting an error as "object expected". please help me
The window.location.search property returns the part of the URL that follows the ? symbol, including the ? symbol.
So for example it might return ?paramname=paramvalue. When you call substring(1) on it you get paramname=paramvalue which is what gets passed to the document.getElementById function which obviously is wrong because such element does doesn't exist on your DOM.
You could use the following javascript function to read query string parameter values:
function onLoad() {
var divname = getParameterByName('divname');
document.getElementById(divname).style.display = 'block';
}
This assumes that you have a query string parameter name called divname:
?divname=some_div_name
Adjust the parameter passed to the getParameterByName function if your query string parameter is called differently.
You might also want to introduce error checking into your code to make it more robust:
function onLoad() {
var divname = getParameterByName('divname');
var divElement = document.getElementById(divname);
if (divElement != null) {
divElement.style.display = 'block';
} else {
alert('Unable to find an element with name = ' + divname);
}
}
What I am suggesting is place your js at the end of the html code (before </body> tag). Do not use a function.
<html>
...
...
...
<body>
...
...
...
<script>
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block";
</script>
</body>
</html>
I have re-written my function and it is working, code is like this
function load()
{
var divname = window.location.search.substring(1);
var params=divname.split('=');
var i=1;
alert(params[i].substring(0));
document.getElementById(params[i].substring(0)).style.display='block';
}
I want to store javascript code in a javascript variable.
To explain clearly, please consider example:
<html>
<body>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<a onclick="toggle_visibility('1');toggle_visibility('2');">Click here to toggle visibility of element </a>
<div id="1">This is 1</div>
<div id="2">This is 2</div>
<script type="text/javascript">
//document.getElementById('2').style.display='none';
</script>
</body>
</html>
Now suppose all this code is in a variable as a string or something. (i want to do this because i am exporting file to another html page where the code should get copied.)
I used all variables such as
using \ before ' and so on. referring to http://www.w3schools.com/js/js_special_characters.asp
Store like this: var myFunc = function(){ do stuff }
Run like this: myFunc();
To interpret JS code you need to use the JS function eval()
var code = "alert('Ok')";
eval(code);
Here is why using eval() is a bad idea:
Why is using the JavaScript eval function a bad idea?
Maybe try something like this:
var quoteElement = document.getElementById('2');
var quote = quoteElement.value;
// or even ..
var quote = document.getElementById('2').value;
You would now have the text value of your element in a variable.
I'm a newb when it comes to javascript. Perhaps somebody could help me with this. I assume it is not very complicated. This is what I would like:
<SCRIPT type=text/javascript>
var StandardURL = "http://site/Lists/test/AllItems.aspx";
</script>
<SCRIPT type=text/javascript>
var FilterURL = "http://site/Lists/test//AllItems.aspx?FilterField1=Judge&FilterValue1=";
</script>
var DynamicURL = FilterURL + DynamicUserInf (no space between it should be like one url link), dynamicuserinf contains different value depending on the user that is logged in no need to worry what is in it. It already contains a value befor this runs
var CurrentURL = current URL where this script is loading
<script language="JavaScript" type="text/javascript">
if (CurrentURL == StandardURL) { location.href= (DynamicURL);}
</script>
ElSE do nothing (i assume this is not neccarry with only one if statement)
Hopefully not much of a mess.
For getting current URL :
var CurrentURL = document.URL;
For joining/concatenating the variables (assuming that DynamicUserInf is a variable), you've already got it correct :)
var DynamicURL = FilterURL + DynamicUserInf;