Javascript Variable Function (Twig) - javascript

My default.htm (to set unique id)
{ % set uid = __SELF__.id % }
<div id="tab" name="{{uid}}" class="my-tab draggable-tab ui-draggable">
<img id="tab-avatar" alt="Virtual agent avatar" style="height:50px; width:50px" src="{{__SELF__.avatarImage}}">
<div id="tab-minimize">
<div id="tab-label"></div>
<div id="tab-expand" name="{{uid}}" class="tab-expand tab-btn"></div>
<div id="tab-close" name="{{uid}}" class="tab-close tab-btn" onclick="tabClose()"></div>
</div>
</div>
JS
function tabClose(){
var uid = document.getElementsByName("name");
$(this).click(function() {
$("#tab").addClass("hidden"); //<--- how to put the uid in?
});
}
JS
var tab_{{uid}} = function tabClose(){
$("#tab-close").click(function() {
$("#tab").addClass("hidden");
});
}
Can someone show me how to use twig in JavaScript?
How to set unique id for each component so that when I duplicate the component it will not have any errors?

You can't call server variable (twig) in client program (javascript).
You must write the twig variable in your html code for javascript catch it.
For example, tout can put it in data attribute.
<div id="tab-close" data-uniqid={{uid}} >
And in your js
var uid = $("#tab-close").data('uniqid');
or with your update
var uid = $("#tab").attr('name');
UPDATE
For your problem, I think You don't need Twig variable in your js, this variable is here to have uniq Id in your html code.
So, try this:
<div id="tab{{__SELF__.id}}" class="my-tab draggable-tab ui-draggable">
<img id="tab-avatar{{__SELF__.id}}" alt="Virtual agent avatar" style="height:50px; width:50px" src="{{__SELF__.avatarImage}}">
<div id="tab-minimize{{__SELF__.id}}">
<div id="tab-label{{__SELF__.id}}"></div>
<div id="tab-expand{{__SELF__.id}}" class="tab-expand tab-btn"></div>
<div id="tab-close{{__SELF__.id}}" class="tab-close tab-btn" onclick="tabClose()"></div>
</div>
And in your js
$(".tab-close").click(function() {
$(this).closest(".my-tab").addClass("hidden");
});

Related

JS function Cant get the Value from vbhtml

How can I get value from my html action link, I tried to set the value in js function and it is work, and the problem is js not get the value form html file, and this forloop only the first one will call the Javascript function.
this is my js function
function selectTemplate() {
$('#choose').on('click', function () {
var objTemplate = $(".styTemplate").val();
$.post(strRoot + "/Home/Index/", { styTemplate: objTemplate });
});
};
and this is my vbhtml code
#For Each item In Model
Dim currentItem = item
'<!-- single-awesome-project start -->
#<div Class="col-md-4 col-sm-4 col-xs-12 #Html.DisplayFor(Function(modelItem) currentItem.strTemplateType)">
<div Class="single-awesome-project">
<div Class="awesome-img">
<img src="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")" alt="" />
<div Class="add-actions text-center">
<div Class="project-dec">
<a Class="venobox" data-gall="myGallery" href="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")">
<h4>#currentItem.strTemplateName</h4>
<span> Web Development</span>
#Html.ActionLink("Choose", "companyInfomation", "Home", New With {.id = "choose"}, New With {.styTemplate = currentItem.strTemplateName})
</a>
</div>
</div>
</div>
</div>
</div>
'<!-- single-awesome-project end -->
Next
</div>
<script>
selectTemplate();
</script>
Maybe it's better to use onclick attribute? Use this instead of Html.ActionLink:
Choose

Pass value to a function in ng-init

I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
Read More . .
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
You need to keep one thing in mind, If you are want your angular code to work on html page, use {{}}. And you do not need these curly braces if you are writing the code with the angular attributes... It means if something is already part of angularjs, you need not to use curly braces.
To solve this issue, you need to replace the below line
<div class="row" ng-init="getImages({{data.id}})">
with this following line
<div class="row" ng-init="getImages(data.id)">
You do not need annotations {{}}
ng-init="getImages(data)
and then inside the controller
$scope.getImages = function(data){
console.log(data.id);
}

How to append blade template in panel-body

I created a two panel one for the user's options and the second panel is the transition of the panel. As you can see below I have a group of buttons every-time the user click the buttons the left panel will changed it's content every-time it clicks. But it won't work if I click on the buttons.
I used empty() so it will be empty first the panel-body on my left container after that I will append in the panel-body section
Master page below.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "{{ URL::asset('css/bootstrap.min.css') }}">
<script type = "text/javascript" src = "{{ URL::asset('js/jquery.js') }}"></script>
<script>
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is subjects");
});
});
</script>
</head>
<body>
#include ('layouts.navigation.user')
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class = "panel panel-default">
<div class = "panel-body" style = "height: 300px">
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "curriculum"> Curriculum
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "subjects"> Subjects
</label><br>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class = "panel panel-default">
<div class = "panel-body" id = "rightContainer" style = "height: 300px; overflow-y: scroll;">
//RIGHT CONTAINER
</div>
</div>
</div>
</div>
</div>
OPTIONS:
subjectsOption
curriculumOption
subjectsOption.blade.php
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "subjectList"> Subject List
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "createSubjects"> Create Subjects
</label><br>
<div>
curriculumOption.blade.php
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "curriculumList"> Curriculum List
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "createCurriculum"> Create Curriculum
</label><br>
</div>
I don't understand why you out checkbox in label. I have just remove the checkbox and add id to labels.
Add insert php file data using html()function.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "{{ URL::asset('css/bootstrap.min.css') }}">
<script type = "text/javascript" src = "{{ URL::asset('js/jquery.js') }}"></script>
<script>
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
//$("#rightContainer").empty();
$("#rightContainer").html(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
//$("#rightContainer").empty();
$("#rightContainer").html(data);
alert("This is subjects");
});
});
</script>
</head>
<body>
#include ('layouts.navigation.user')
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class = "panel panel-default">
<div class = "panel-body" style = "height: 300px">
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg" id = "curriculum">
Curriculum
</label><br>
<label class = "btn btn-primary btn-lg" id = "subjects">
Subjects
</label><br>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class = "panel panel-default">
<div class = "panel-body" id = "rightContainer" style = "height: 300px; overflow-y: scroll;">
//RIGHT CONTAINER
</div>
</div>
</div>
</div>
</div>
Laravel Blade Template, or PHP file inside the /resources/views inside Laravel framework is not accessible using URL directly, to be precise, everything under /resources folder and even all other folders except /public, are not accessible. Only public folder can be accessed directly by using URL in laravel framework. You must notice that the view inside resources folder can only be returned after come from route -> controller -> view to be simple.
Thus, this part of your code
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is subjects");
});
});
is trying to access your server in certain URL. lets take example your domain is test.laravel.dev and you are in root of your domain (in your browser you can see http://test.laravel.dev), and you run these script there. It means that you are trying to do AJAX request to url http://test.laravel.dev/curriculumOption.blade.php and http://test.laravel.dev/subjectOption.blade.php. What will happens? this will try to find route in your routes.php file, looking for "/curriculumOption.blade.php" or "/subjectOption.blade.php" which i am sure it's not exists there. what you can do is, if you still need the blade template to be processed before returning as AJAX response, you can make it like this:
routes.php
Route::get("/curriculumOption","CurriculumOptionController#show");
CurriculumOptionController.php
public function show()
{
//do your things here
return view("curriculumOption");
}
with the curriculumOption.blade.php is under /resources/views folder, and change your ajax request to:
$(document).on("click", "#curriculum", function ()
{
$.get("/curriculumOption", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
This will work, please try and ask if have any other problem.
Explanation #1
Due to some security reason and also as a feature for laravel, most of the folders except public cannot be accessed without PHP preprocessor. When you are making a request in browser, the HTTP request is being sent to your browser to the server. in this case, if you make get request, you dont pass any other additional form parameters to server. Server read the request URL from your browser and then there are some server configuration in how are they going to pass the parameter to PHP preprocessor. These configuration is set in .htaccess file for apache HTTP server, nginx configuration for NGINX, and web.config for IIS server. You can notice that the .htaccess file is included in your /public folder of laravel project and the /public folder is the default for your domain, lets say your domain is test.laravel.dev, then test.laravel.dev is equal to /public and test.laravel.dev/index.php is refering to /public/index.php file. The rest that can be put in /public usually are css, javascript, and image files. Templates, Controller, Routes, etc are not accessible from URL. They are being managed by the framework. /resource folder is not accessible for security reason also. The only way is to access it from route or controller. If you dont define what to do with a certain URI, laravel framework will not give a proper response which is most likely erorr. Your /management/curriculumOption.blade.php can't be accessed simply because you dont have a route with
Route::get("/management/curriculumOption.blade.php"/, .....)
even though i dont think you can put .blade.php in the parameters also, but worth to try. There are only 2 options(need citation) to access certain URL to be responded in Laravel:
Define it in routes.php
put it in public folder

jQuery script works just for one button on the product catalog

I have a product catalog and I want to save on localstorage the products selected by the user.
The jquery script only gets the first product on each page on each click... it simply ignores the rest of the products, and the console prints the same object.
Here is my HTML+TWIG code
{% for products in pagination %}
<div class="product col-sm-6 col-lg-6 col-md-6 hero-feature">
<div id="{{attribute(products ,'id')}}" class="product thumbnail">
<img id="prodImage" class="img-responsive img-rounded" src="{{attribute(products ,'image')}}" style="width:150px;height:150px" >
<div class="product caption">
<h4 id="prodPrice" class="product pull-right"><b>{{ attribute (products, 'price') }}Lei</b></h4>
<h4 id="prodName" style="height:100px;width:200px;">
<a id="prodLink"
href="{{ attribute (products, 'affiliatelink') }}"
target="_blank">{{attribute ( products, 'name') }}</br></a>
</h4>
</div>
<div class="add-to-cart" class="product" >
<button id="buttonProd" class="oneButton btn btn-danger " value="Save" type="button">Adauga</button>
</div>
</div>
</div>
{% endfor %}
Here is the jquery script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type='text/javascript' defer="defer">
$(document).ready(function() {
var prodId = $('.thumbnail').attr("id");
$("#buttonProd").on("click", 'button', function(event){
event.preventDefault();
var products =
{
prodID :$('.thumbnail').attr("id"),
prodName :$('#prodName').text(),
prodPrice :$('#prodPrice').text(),
prodImage :$('#prodImage').attr('src'),
prodLink :$('#prodLink').attr('href')
};
localStorage.setItem('products-' + prodId, JSON.stringify(products));
var retrievedObject = JSON.parse(localStorage.getItem('products-' + prodId));
console.log('retrievedObject: ', retrievedObject);
});
});
</script>
How can I make the script take each product proprieties on click. Thank you in advance.
In JQuery, the assumption is made that all ID's will be unique. Since you're repeating "#buttonProd", JQuery will only select the first one to bind the action to. If you want to bind to multiple elements, you'll either have to give each button a unique ID or use some other selector to attach your jQuery functionality.
From the documentation for the ID Selector:
Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.
As the other answers have eluded to you should be using a different selector. I recommend simply adding a descriptive class to each element you wish to grab data from.
<div class="products">
<div class="product">
<div class="productName">First Product</div>
<div class="productPrice">5.00</div>
</div>
<div class="product">
<div class="productName">Second Product</div>
<div class="productPrice">4.00</div>
</div>
<button id="buttonProduct">Log Product Info</button>
</div>
If you notice in the above HTML each div that contains a product's name or a product's price shares the same class productName and productPrice respectively. In addition each container class for each product has the same class as well: product.
This will allow us to utilize the JQuery class selector $(".") to iterate over each product container. We do this using the .each() function. We use the .find() function to locate productName and productPrice in each iteration of the loop.
$(document).ready(function() {
$("#buttonProduct").click(function(){
var products = [];
// Notice the dot in $(".product") that is the class selector
// the .each iterates over every element that matches the preceding selector
$(".product").each(function(){
products.push({
// The .find() selects an element inside $(this)
// that matches the parameter (either .productName or .productPrice
productName : $(this) .find('.productName').html(),
productPrice : $(this).find('.productPrice').html()
});
});
console.log(products);
});
});
For a working example of this check out this jsfiddle. (I noticed you had console.log() in your code so that's where I output the result.)
You want to save the product in localStorage on clicking of corresponding button right?
for that instead of binding click event via jquery, put it in html and move the click code to a function saveProduct()
HTML:
<button id="buttonProd" class="oneButton btn btn-danger " value="Save" type="button" onclick="saveProduct({{attribute(products ,'id')}})">Adauga</button>
JS:
function saveProduct(event, prod_id){
event.preventDefault();
var products =
{
prodID :prod_id,
prodName :$('#'+prod_id+' #prodName').text(),
prodPrice :$('#'+prod_id+' #prodPrice').text(),
prodImage :$('#'+prod_id+' #prodImage').attr('src'),
prodLink :$('#'+prod_id+' #prodLink').attr('href')
};
localStorage.setItem('products-' + prod_id, JSON.stringify(products));
var retrievedObject = JSON.parse(localStorage.getItem('products-' + prod_id));
console.log('retrievedObject: ', retrievedObject);
});
}
You need to change #buttonProd from an id to a class. An id is only supposed to appear once on a page, so jQuery will only apply it to one. Change it to a class in your markup and your script and it should work fine. Same for prodName, prodPrice, prodImage, and prodLink. Anything that will be going inside the loop needs to be a class, and any id should be unique, like you have {{attribute(products ,'id')}}

How to pass the values to the other html page and redirect the to that page for onclick thumbnail using jquery?

Here I need to click on a thumbnail, so that it will show the details on other page, it should show the details of that particular thumb only. I used xml file here to fetch the data and display thumbnail. I am unable to pass the values to other page and open it at the same time onclick event. pls help
<div class="container-page">
<div class="row" id="portfolio">
<div class="col-md-2">
<nav>
<ul class="nav nav-pills nav-stacked" id="test">
<li role="presentation" class="active">Services</li>
<li role="presentation">Desktop</li>
<li role="presentation">Web</li>
<li role="presentation">Mobile</li>
<li role="presentation">Design</li>
</ul>
</nav>
</div>
<div class="col-md-10">
<div class="row" id="thumb">
</div>
</div>
</div>
</div>
<!-- js -->
$.ajax({
type:"GET",
url:"portfolio.xml",
dataType:"xml",
success:function(xml)
{
$(xml).find('thumbnail').each(function()
{
var $thumbnail=$(this);
var type=$thumbnail.find('type').text();
var descr=$thumbnail.find('description').text();
var title=$thumbnail.attr('title');
var imageurl=$thumbnail.attr('imageurl');
var thum='<div class="col-xs-6 col-md-3"> </div>';
thum=$(thum).appendTo("#thumb");
thum = $('').appendTo(thum);
var thumName = $('<div class="thumTitle"></div>').appendTo(thum);
$('<h2>'+title+'</h2>').appendTo(thumName);
$('<p>'+type+'</p>').appendTo(thumName)
thum = $('<img src="'+imageurl+'" alt="image" class="thumbImgSize imgSlide">').appendTo(thum);
$(".forHove").mouseup(function()
{
//here is the redirection code, and want to pass $thumbnail to testxml.html page
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
});
}
});
Well, one of the alternative is using Web Storage API.
Just store img html and use it.
// use 'click' instead of 'mouseup'
$(".forHove").click(function()
{
// store image html to sessionStorage
window.sessionStorage.image_data = $thumbnail.clone().wrapAll("<div>").parent().html();
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
// in http://www.bookmane.in/skillworks/testxml.html
// You have data sotred and insert it somewhere
$(document.body).append(window.sessionStorage.image_data);
You can achieve this thing using the following steps:
Add a form tag like
<form action="YOUR_PATH" method="GET">
<a class="thubnailClick" href="#" >
<html_of_your_thumbnail>
<input type="text" name="NAME_OF_PARAMETER" />
</a>
</form>
Now override the click event of <a> tag with
$(document).ready(function() {
$(".thubnailClick").on('click', function(event) {
// to override the default behavior of <a> tag.
preventDefault();
// Find the form element using closest() of jQuery.
// Call submit event of that form using $(form_element).submit();
});
})
Now on the other page you can get parameter from URL using location.search or follow:
Getting Query params using JavaScript
Now use these Params according to your needs.

Categories

Resources