Including smarty in javascript - smarty

<script type="text/javascript">
var cutValue = plgShirt.getValueCut();
{limiter}$cutValue{/limiter} = cutValue;
</script>
I want to assign a smarty variable to a java script variable that can help me.

you can try this
<script type="text/javascript">
var cutValue = 1;
var {$cutValue} = cutValue;
for(let b in window) {
if(window.hasOwnProperty(b)) console.log(b);
}
</script>

Related

JQueryUI autocomplete search with Django not working

I am working on a project with Django, for a restaurant management system. I wanted to use an autocomplete feature to take orders at the table.
As far as I understand JQueryUI function autocomplete() is what I need.
However I cannot seem to get it to work.
Following is my my HTML code for the page. It works in such a way that once the number of people in the party is inserted the same number of form input fiels is inserted in the table by a Javascrip script.
addOrder.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script type="text/javascript" src={% static "js/jquery-3.3.1.min.js" %}></script>
<script src={% static "js/jquery-ui.min.js" %}></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src={% static "js/createOrderIn.js" %}> </script>
<script type="text/javascript" src={% static "js/autocompleteDrink.js" %}></script>
<script type="text/javascript" src={% static "js/autocompleteMenu.js" %}></script>
<style>
.move {
margin: 30px;
}
</style>
<title>Add Order</title>
</head>
<body>
<div class="move">
<form action="/orders/addOrder" method="post" id="the-form" class="ui-widget">
<label> Party of </label>
<input type="text" id="people">
<input type="submit" class="btn btn-primary" value="Submit order">
</form>
</div>
</body>
</html>
This is the script I use to spawn new form input fields
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" id=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" id=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
The following are the relative Python/Django files
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ordersIndex, name = "index"),
path('changeStatus/<int:pk>', views.changeStatus, name="changeStatus"),
path('addOrder', views.addOrder, name="addOrder"),
path('addOrderRender', views.addOrderRender, name="addOrderRender"),
path('getDrinks', views.getDrinks, name="getDrinks"),
path('getMenus', views.getMenus, name="getMenu"),
]
views.py (only function getMenus())
def getMenus(request):
print("I am called")
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['name'] = menu.name
menu_json['n_courses'] = menu.number_of_courses
menu_json['price'] = menu.price
results.append(menu_json)
data = json.dump(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
And lastly this is the function that is supposed to use JQueryUI to make the ajax call and retrieve the possible menu's
autocompleteMenu.js
$(function() {
$("#menu").autocomplete({
source: "/orders/getMenus/",
});
});
As you can probably see from the getMenus() function in views.py I also print a check line ("I am called"), which sure enough does not get printed on console. Also even by switching the autocomplete() source parameter to a local array there is no result.
I do feel like I am doing some very naive mistake but I really cannot seem to figure it out (I am also pretty new with JQuery).
I think the error should be in the provided files, but I'll be happy to post edits in just in case
Thank you in advance!
I realized that the problem was due to the fact that I had to bind autocomplete to the id of the newly created id's (which I changed to classes). Also the JSON data must have a lable field, (and I had to use json.dumps(), not json.dump() :p).
The followings did the trick:
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" class=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" class=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
$('#the-form').find('input[class=menu]:last').autocomplete({
source: "/orders/getMenus"
});
$('#the-form').find('input[class=drink]:last').autocomplete({
source: "/orders/getDrinks"
});
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
views.py
def getDrinks(request):
if request.is_ajax():
q = request.GET.get('term', '')
drinks = Drink.objects.filter(name__contains=q)
results=[]
for drink in drinks:
drink_json = {}
drink_json['label'] = drink.name
results.append(drink_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def getMenus(request):
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['label'] = menu.name
menu_json['id'] = menu.number_of_courses
results.append(menu_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Create addListener click event for more than one shape on the Google map

Look at this code:
This creates four circles on the map in a same position and it creates addListener click event for each one too but I just can click on the last one. I want to fix it in a way that I can click on all of them to make setEditable(true) for each one.
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var selectedShape;
function clearSelection()
{
if(selectedShape)
{
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape)
{
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
</script>
<script>
var amsterdam=new google.maps.LatLng(52.395715,4.888916);
function initialize()
{
var mapProp = {center:amsterdam, zoom:7, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myArray = [];
var myCity;
for(var i = 0; i < 4; i++)
{
myCity = new google.maps.Circle({
center:amsterdam,
radius:20000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
myArray.push(myCity);
google.maps.event.addListener(myCity, 'click', function() {setSelection(myCity)});
myArray[i].setMap(map);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
Use this instead of myCity :
google.maps.event.addListener(myCity, 'click', function() {
setSelection(this)
});
Using setSelection(myCity) will refer to the last myCity created.

How do I get a working example more compliant with the basics of jquery plugins

My first fumbling with jquery plugins wwning myself off DOM object manipulation.
I have read so much about plugins that it is making my brain hurt. Although I have got the plugin to do what is expected. I can't believe the way I've set the variables and initialisation is correct. While not requiring all eventualities to be addressed, I would be grateful if you could comment on the more non-compliant aspects in order that future plugins can be tackled with a degree of confidence. Example http://www.wordscans.com/jtest/ (ignore outer ring)
The Code..
enter code here
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD>
<script type=text/javascript src="jquery.min.js"></script>
<script type=text/javascript src='RkJQRotate.js'></script>
<script type=text/javascript>
function kickoff() {makeins(); ringpos();
setTimeout('$("").rotateinner()',200); $('#ovobj').rotoval();}
function makeins() {
jQuery('<div></div>',{'id': 'tmplx','lft':'-90','top':0, 'ang':0}).addClass ('incirc').appendTo('body');
for(var i=0; i<4; i++) {idrf='incir'+i; var img='pic/rot'+i+'.gif';
$('#tmplx').clone().attr('id',idrf).css({'background-image':'url("'+img+'")'}).appendTo('body');}
$('#ovalob').clone().attr('id','ovobj').appendTo('body').fadeIn(40);
$('#ovobj').css({left:'50px',top:'50px','display':'block'}).fadeIn(40);}
function ringpos() {var coord=$('#ringhold').offset(); VposX=coord.left; VposY=coord.top;
var inca=360/Velnum; Vstang=Vstang%360; var sang=Vstang; var rad=Vdiam/2; var offs=((Vringw-Vwdh)/2);
for(var i=0; i<4; i++) {var erf='#incir'+i; var quadr=Math.floor(sang/90); var cang=sang%90;
var ang=cang*(Math.PI/180); sang+=inca;/*radians*/
var x=rad*Math.cos(ang); var y=rad * Math.sin(ang); xx=(quadr%2)?x:y; yy=(quadr%2)?y:x;
xx=(quadr>1)?-xx:xx; yy=(quadr%3)?yy:-yy; erf='#incir'+i; rlt=VposX+xx+offs; rtp=VposY+yy+offs;
$(erf).css({left:rlt+'px',top:rtp+'px','display':'block'}).fadeIn(40);} }
var Vdiam=152; var Velnum=4; Vwdh=98; Vht=98; Velm='ringhold'; Vstang=45; Vringw=300; Vinc=-2.001; var VposX; var VposY;
(function($) {
var inca=360/Velnum; inca=(Vinc<0)?-inca:inca; var rad=Vdiam/2; var offs=((Vringw-Vwdh)/2);
var trig=1; var trigovl=1; var intval=null; var intvalo=null;
//rotateinner=function ()
$.fn.rotateinner=function () {/* return setInterval(function() Dont try chaining* with return*/
if(trig==0) { clearInterval(intval); return}
intval=setInterval(function() {var v=Vstang+Vinc; Vstang=(v>360)?v%360:(v<0)?360+v:v; var sang=Vstang;
for(var i=0; i<4; i++) {var erf='#incir'+i; var quadr=Math.floor(sang/90); var cang=sang%90;
var ang=cang*(Math.PI/180); v=sang+inca; sang=(v>360)?v%360:(v<0)?360+v:v;; /*radians*/
var x=rad*Math.cos(ang); var y=rad * Math.sin(ang); xx=(quadr%2)?x:y; yy=(quadr%2)?y:x;
xx=(quadr>1)?-xx:xx; yy=(quadr%3)?yy:-yy; erf='#incir'+i; rlt=VposX+xx+offs; rtp=VposY+yy+offs;
$(erf).css({left:rlt+'px',top:rtp+'px'}); }; }, 85); }
var lgrad=230; var smrad=120; var stang=45; var oincr=2.2; var low=280;
$.fn.rotoval=function() {
if(trigovl==0) { clearInterval(intvalo); return}
jqobj='#'+this.attr('id');
intvalo=setInterval(function() {
if($(jqobj).attr('oang')==undefined) {$(jqobj).attr('oang',stang);}
oang=$(jqobj).attr('oang');
var quadr=Math.floor((oang)/90); var rnang=(oang%90); rnang=(rnang)?rnang:0.01;
if(quadr%2){rnang=90-rnang;} var rnang=rnang*(Math.PI/180);
var frma=lgrad*smrad; var frmb=Math.pow(smrad*Math.sin(rnang),2);
var frmc=Math.pow(lgrad*Math.cos(rnang),2)
var radfac=frma/Math.sqrt(frmb+frmc);
var x=radfac*Math.sin(rnang);var y=radfac*Math.cos(rnang);
xx=(quadr<2)?x:-x; yy=(quadr%3)?y:-y;
rlt=VposX/1+xx/1+offs; rtp=VposY/1+yy/1+offs+low;
$(jqobj).css({'left':rlt+'px','top':rtp+'px'});
var v=oang/1+oincr+0.001; oang=(v>360)?v%360:(v<0)?360+v:v;
$(jqobj).attr('oang',oang);}, 80); }
})(jQuery);
<style>
.incirc {display:none;position:absolute;width:98px;height:98px;z-index:20}
</style>
</head>
<body onload=setTimeout('kickoff()',100);>
<div id='ringhold'><div id='ringbs'></div><div id='ringtp'></div><div id='ovalob' class='ovalob''></div></div>
</body></HTML>
Thanks for any possible help with this AND THANKS to all who who have spent time contibuting to this site as a first stop when priblems arise.

jquery error while embedding external javascript in drupal 7

I have a javascript code which is :
<script type="text/javascript">
(function ($) {
var speed = 50;
var pic, numImgs, arrLeft, i, totalWidth, n, myInterval;
$(window).load(function(){
pic = $("#slider").children("img");
numImgs = pic.length;
arrLeft = new Array(numImgs);
for (i=0;i<numImgs;i++){
totalWidth=0;
for(n=0;n<i;n++){
totalWidth += $(pic[n]).width();
}
arrLeft[i] = totalWidth;
$(pic[i]).css("left",totalWidth);
}
myInterval = setInterval("flexiScroll()",speed);
$('#imageloader').hide();
$(pic).show();
});
function flexiScroll(){
for (i=0;i<numImgs;i++){
arrLeft[i] -= 1;
if (arrLeft[i] == -($(pic[i]).width())){
totalWidth = 0;
for (n=0;n<numImgs;n++){
if (n!=i){
totalWidth += $(pic[n]).width();
}
}
arrLeft[i] = totalWidth;
}
$(pic[i]).css("left",arrLeft[i]);
}
}
}(jQuery));
</script>
If I remove the embedding function tag (function ($) { i get an error of Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function and if I enclose it in that tag i get Uncaught ReferenceError: flexiScroll is not defined
How to solve this problem?
Is it not supposed to be })(jQuery);?
Not a jQuery expert at all but that's what I have in my scripts?
setInterval() is a standard Javascript Function not JQuery.
You can call it using it like this
myInterval = setInterval(function() {
flexiScroll();
},2000);

jquery plugin problem

i created jquery plugin
and error I get is reference error: mySlider is not defined
(function($){
$.fn.mySlider = function(){
var timeOut = 4000;
var element = this;
var fxDuration = timeOut/6;
var items = $("#" + element[0].id + " li");
var captions = $("#" + element[0].id + " li div");
var fadeIn = function(no){
$(items[no]).fadeIn(fxDuration, function(){
$(captions[no]).fadeIn(fxDuration, function(){
setTimeout(function(){fadeOut(no)}, timeOut);
});
});
}
var fadeOut = function(no){
$(captions[no]).fadeOut(fxDuration, function(){
$(items[no]).fadeOut(fxDuration, function(){
fadeIn(calcNext(no));
});
});
}
var calcNext = function(no){
return ((no+1) == items.length)? 0: (no+1);
}
fadeIn(0);
}
})(jQuery);
and called
<script src="jquery-1.6.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="mySlider.js" type="text/javascript" charset="utf-8"></script>
<script>
// alert('hi');
$(document).ready(function(){
alert(mySlider());
//$("#slider").mySlider();
});
</script>
It says mySlider is not defined
please help me to solve this. Thanks
It is not defined, since you did not define it.
You defined only $.fn.mySlider
You may want something like this, to have a separate function:
var mySlider = function() {
$("#slider").mySlider();
};

Resources