I just worked through the Google Polymer tutorial and I am building my first own element. And I am missing some DOM-Scripting Functions I know from Prototype and jQuery that made my life very easy. But maybe my methods are just not right. This is what I have done so far:
<polymer-element name="search-field">
<template>
<div id="searchField">
<ul id="searchCategories">
<li><a id="search-categories-text" data-target="text" on-click="{{categoryClick}}">Text</a></li>
<li><a id="search-categories-videos" data-target="videos" on-click="{{categoryClick}}">Videos</a></li>
<li><a id="search-categories-audio" data-target="audio" on-click="{{categoryClick}}">Audio</a></li>
</ul>
<div id="searchContainer">
<input id="searchText" type="text" />
<input id="searchVideos" type="text" />
<input id="searchAudio" type="text" />
</div>
</div>
</template>
<script>
Polymer({
ready: function() {
},
categoryClick: function(event, detail, sender) {
console.log(sender.dataset.target);
console.log(this.$.searchField.querySelector('#searchContainer input'));
this.this.$.searchField.querySelector('#searchContainer input');
}
});
</script>
</polymer-element>
What I want to do is to set an active class to the bottom input-fields when one of the above links are clicked. On jQuery I would just observe a link and deactivate all input fields and activate the one input field I want to have. But I am not sure how to do it without jQuery. I could just use all the native javascript functions with loops etc but is there anything polymer can offer to make things easier?
Does this example do what you want?
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/platform.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/polymer.js"></script>
<polymer-element name="search-field">
<template>
<style>
.hideMe {
display: none;
}
</style>
<div id="searchField">
<ul id="searchCategories">
<template repeat="{{category in searchCatergories}}">
<li><a on-click="{{categoryClick}}">{{category}}</a></li>
</template>
</ul>
<div id="searchContainer">
<template repeat="{{category in searchCatergories}}">
<div class="{{ { hideMe: category !== selectedCategory} | tokenList }}">
<label>Search for {{category}}</label>
<input id="search{{category}}" type="text">
</div>
</template>
</div>
</div>
</template>
<script>
Polymer({
searchCatergories: [
"Text",
"Video",
"Audio"
],
selectedCategory: 'Text',
categoryClick: function(event, detail, sender) {
// grab the "category" item from scope's model
var category = sender.templateInstance.model.category;
// update the selected category
this.selectedCategory = category;
// category
console.log("category", category);
// you can also access the list of registered element id's via this.$
// try Object.keys(this.$) to see registered element id's
// this will get the currently showing input ctrl
selectedInputCtrl = this.$["search" + category];
}
});
</script>
</polymer-element>
<search-field></search-field>
I've created an array for the categories and added two repeat templates.
I've setup a .hideMe class which is set on all input elements that aren't the currently selected category.
Info on dynamic classes - https://www.polymer-project.org/docs/polymer/expressions.html#tokenlist
Info on repeat - https://www.polymer-project.org/docs/polymer/binding-types.html#iterative-templates
Hope that helps
Related
I have an array of objects. These objects are loaded into a list in vue.js.
Aside from this list, I have a form that displays data from one of these objects. I want to, when clicking one of the list's elements, it will bind this specific object to the form and show its data.
How can do this in Vue.js?
My list code is:
<div id="app-7">
<ul id="food-list" v-cloak>
<food-item v-for="item in foodList" v-bind:food="item" v-bind:key="item.id" inline-template>
<li class="food">
<div class="food-header">
<img :src="'img/' + food.slug +'.png'">
<div class="food-title">
<p>{{food.name}} |
<b>{{food.slug}}</b>
</p>
<p>quantity: {{food.quantity}}</p>
</div>
<div class="food-load"> // load into form upon clicking this
</div>
</div>
</li>
</food-item>
</ul>
</div>
Since I do not have the code for the form, this is my best guess without clarification.
You can add a click handler to the item you want to be clicked. It will pass the value of the food item into the method.
<div class="food-load" #click="setFoodItem(item)">
</div>
And when that method is called, it can assign the clicked item to a data property. I'm not sure where your form is, and if it is in a different component. If it is in a child component, you would have to pass it in as a prop, or emit an event to pass it to a parent component.
data() {
return {
//create a reactive field to store the current object for the form.
foodItemForm: null
};
},
methods: {
//method for setting the current item for the form.
setFoodItem(item) {
this.foodItemForm = item;
}
}
Missing quite a bit of info in your sample code, your script is very important to see to make sense of what you would like to accomplish and where things might be going wrong.
Here's a quick list of the issue I came across with your code:
v-for refers to an individual food item as 'item', inside the loop you're trying to access properties as 'food'
You don't wrap your code in a component unless you're importing the component
When binding a value to 'v-bind:src' (or shorthand ':src') only pass the url, you should be specifying this in your script not inline.
You're better off using a button and the 'v-on:click' (or shorthand '#click') to load your selected food item into your form
You should also include your Javascript
Regardless, here's how I would handle this (took the liberty in filling in some blanks):
<template>
<div id="app">
<ul id="food-list">
<!--<food-item v-for="item in foodList" v-bind:food="item" v-bind:key="item.id" inline-template>-->
<li v-for="item in foodList" class="food">
<div class="food-header">
<img :src="item.slug" v-bind:alt="item.slug" width="250px" height="auto">
<div class="food-title">
<p>{{item.name}} | <b>{{item.slug}}</b></p>
<p>quantity: {{item.quantity}}</p>
</div>
<button class="food-load" #click="loadFoodItem(item.id)">Load Food Item</button>
</div>
</li>
<!--</food-item>-->
</ul>
<form v-if="activeFoodId != null" id="foodItemForm" action="#">
<h3>Food Form</h3>
<label for="food-id">Id:</label>
<input id="food-id" type="number" v-bind:value="foodList[activeFoodId].id"><br/>
<label for="food-slug">Slug:</label>
<input id="food-slug" type="text" v-bind:value="foodList[activeFoodId].slug"><br/>
<label for="food-name">Name:</label>
<input id="food-name" type="text" v-bind:value="foodList[activeFoodId].name"><br/>
<label for="food-quantity">Quantity:</label>
<input id="food-quantity" type="number" v-bind:value="foodList[activeFoodId].quantity">
</form>
</div>
</template>
<script>
export default {
name: 'app',
data: function () {
return {
activeFoodId: null,
foodList: [
{
id: 1,
slug: 'http://3.bp.blogspot.com/-QiJCtE3yeOA/TWHfElpIbkI/AAAAAAAAADE/Xv6osICLe6E/s320/tomato.jpeg',
name: 'tomatoes',
quantity: 4
}, {
id: 2,
slug: 'https://img.purch.com/rc/300x200/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzA2NS8xNDkvb3JpZ2luYWwvYmFuYW5hcy5qcGc=',
name: 'bananas',
quantity: 12
}, {
id: 3,
slug: 'https://media.gettyimages.com/photos/red-apples-picture-id186823339?b=1&k=6&m=186823339&s=612x612&w=0&h=HwKqE1MrsWrofYe7FvaevMnSB89FKbMjT-G1E_1HpEw=',
name: 'apples',
quantity: 7
}
]
}
},
methods: {
loadFoodItem: function (foodItemId) {
console.log(foodItemId)
this.activeFoodId = foodItemId
}
}
}
</script>
<style>
/# Irrelevant #/
</style>
Hope it helps!
I am fairly new to jQuery, and even though there are a lot of tutorials on how to bind to buttons, I believe my set up is a little more complicated (beyond the scope).
What I have:
-I am using Django to populate my Makes on a view.
Here is my template:
<div class="container">
<div class="row">
<div class="btn-group" id="makesTable">
{% if makes %}
{% for make in makes %}
<button type="button" name="button" class="btn btn-default" id="{{ make.id }}">
<br />
<img class="center-block" src="[REDACTED]" />
<br />
<p>{{ make.name }}</p>
</button>
{% endfor %}
{% endif %}
</div>
</div>
</div>
I am currently having an issue with responsive design. I would like for the buttons to be arranged in a 5x7 grid, however, sometimes, I get the following issue:
This is how it looks when everything is good!
This is the problem. Notice the spacing with a ?
The Workflow:
User sees (35) different buttons to select from. As you can see name, and id are unique, where id is the Primary Key from the database (this is obviously important)
I can capture the primary key using jQuery using this function:
$(document).ready(function() {
$("button").click(function() {
var make_id = $(this).attr('id')
});
});
At the same time, jQuery is going to hide/remove the button elements (trivial)
This is done with the following code snippet (anf adding fadeout to the click listener:
function fadeOut() { $( "#makesTable" ).fadeOut( "slow", function() {}); };
Then I would like to use the id from button clicked to do an AJAX request to my API, where django URL routing is:
url(r'^makes/(?P<pk>[\d]+)/$', views.MakesDetail.as_view(), name='makes-instance'),
in other words, the AJAX request goes to mysite.com/api/makes/(this.id) and returns a JSON file (already set-up thanks to DRF.)
Sample Response:
{
"name": "BMW",
"model": [
{
"name": "2 Series",
},
{
"name": "3 Series",
}]
}
Finally, using this API response, I wish to populate a similar template of buttons (replacing makes with models.)
This is for a single page app in a sense where no page refresh is necessary with the use of JSON and AJAX.
Full disclosure: I am an entry level programmer/web developer.
code snippet:
<div class="main-content container-fluid">
<div class="container">
<div class="row">
<div class="btn-group" id="makesTable">
<button type="button" name="button" class="btn btn-default" id="200002038">
<br />
<img class="center-block" src=" " />
<br />
<p>Acura</p>
</button>
<button type="button" name="button" class="btn btn-default" id="200464140">
<br />
<img class="center-block" src="" />
<br />
<p>Alfa Romero</p>
</button>
<script>
$(document).ready(function() {
$(document).on( "click", "button", function() {
alert($(this).attr('id')); //testing functionality
});
});
</script>
<script src="assets/lib/jquery/jquery.min.js" type="text/javascript"></script>
<script src="assets/lib/perfect-scrollbar/js/perfect-scrollbar.jquery.min.js" type="text/javascript"></script>
<script src="assets/js/main.js" type="text/javascript"></script>
<script src="assets/lib/bootstrap/dist/js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
//initialize the javascript
App.init();
});
</script>
</div>
</div>
</div>
</div>
Since the buttons are dynamically generated. You have to make the handler like this:
$(document).on('click', 'button.btn', function(e) {
alert($(this).attr('id')); //testing functionality
});
First of all, event association to buttons should be better via classes (it's a better practice).For the javascript click code check the other answers.
For ajax requests, you can refer to this links:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.when/
By example 'when' function, it allows you to know when request ended and execute any actions after.
from your replied comment I expect that you attach the handler before the button already rendered so I recommend you to use bubbling event concept like this:-
$(document).ready(function() {
$(document).on( "click", "button", function() {
alert($(this).attr('id')); //testing functionality
});
});
and the the alert will pop up and you can do whatever else you want to do.
Here is my piece of code, a function to add a meal template:
vm.addMealTemplate = function() {
$scope.mealCount++;
$compile( $(document.createElement('div')).attr("id", 'mealDiv' + $scope.mealCount).addClass("mealDiv"+$scope.mealCount).after().html(
'<select ng-options="(option.name ) for option in mealOptions" ng-model="selectedOption'+ $scope.mealCount+'" />' +
'<input type="text" placeholder="Meal timings" id="time'+ $scope.mealCount +'"/>' +
'<a id="mealCount" ng-class="mealCount" ng-click="addItemCategory()" uib-tooltip="Add category" tooltip-trigger="mouseenter" tooltip-placement="bottom"><i class="fa fa-plus"></i></a>'
).appendTo("#meals")
// $("#meals").append(newMealDiv)
)($scope);
}
On clicking calling the addItemCategory() for the specific div, I want another div to get added as a child of that div. There can be mutiple meal templates, and for each template I can call the addItemCategory mutliple times, and I want the category to be added to the same div for which the function has been called. How do I achieve this?
Currently I am using mealCount variable from scope to have the context, but once it gets increased, I have no way to access the divs added previously, to add the new element to that div. Any way using jQuery or AngularJs?
You can use ng-repeat
For example:
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.meals = [];
});
.meal {
border:1px solid;
padding:10px;
margin-bottom:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="meal in meals" class="meal">
<select ng-model="meal.count">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" placeholder="Meal timings" ng-model="meal.timing" />
<div>
<div>Categories:</div>
<div ng-repeat="cat in meal.categories track by $index">
<input type="text" ng-model="meal.categories[$index]" />
</div>
<button ng-click="meal.categories.push('')">Add Category</button>
</div>
</div>
<button ng-click="meals.push({categories:[]})">Add meal</button>
<hr />
{{meals | json}}
</div>
Note: I changed the models etc. it's just example..
Here's an example Plunker on how your problem can be solved with ng-repeat in Angular:
http://plnkr.co/edit/POt7nFc4GqFU67SWdMp7?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="restaurant" ng-controller="meal-controller">
<div ng-repeat="meal in meals track by $index">
<select ng-options="option.name for option in mealOptions" ng-model="meal.selectedMeal"></select>
<input type="text" placeholder="Meal timings" id="{{'time'+ $index }}" ng-model="meal.timing"/>
<a id="mealCount" ng-class="mealCount" ng-click="addItemCategory()" uib-tooltip="Add category" tooltip-trigger="mouseenter" tooltip-placement="bottom"><i class="fa fa-plus"></i></a>
</div>
<button ng-click="addMeal()">Add meal</button>
</body>
</html>
-
// Script.js
angular.module('restaurant', [])
.run( ['$rootScope', function( $rootScope ) {
}]
);
angular.module('restaurant').controller('meal-controller', [ '$scope', function( $scope ) {
$scope.meals = [];
$scope.mealOptions = [{ name: "option1"}, { name: "option2"}, { name: "option3" } ];
$scope.addMeal = function() {
$scope.meals.push({ selectedMeal: null, timing: "timing" });
}
$scope.addItemCategory = function() {
}
}]);
I am not entirely sure about how you want the logic to work, but I am sure that you can modify this example to fit your needs.
Ng-repeat works like a loop which prints the content it is wrapping until the end of the array. Ng-repeat has a lot of features like tracking elements in the array by index, this can used to (like in the example) give each input an unique id.
If you need to make some specific changes to a meal, you can pass it as an argument, for example if you want to delete a specific meal you can have a button inside the ng-repeat like this:
<button ng-click="deleteMeal(meal)">Delete Meal</button>
This means that you do not have to access the meal specifically by, for example, its id with jQuery.
I would say it is not recommended to mix angular and jQuery the way you are doing now. Try to stick with Angular and avoid jQuery. In some special cases where you need to do element specific modifications it can be achieved by using jQlite:
https://docs.angularjs.org/api/ng/function/angular.element
I'm trying to include a unique id for an and tag to get a custom checkbox. The {{input}} tag outputs it correctly but the <label {{bind-attr for=binding}} does not. I'm a frontend guy new to Ember so I'm sure this should be trivial.
<ul class="col-menu dropdown-menu">
{{#each columns}}
<li>
{{input type="checkbox" checked=checked id=binding}}
<label {{bind-attr for=binding}}><span></span></label>
<span>{{heading}}</span>
{{columns}}
</li>
{{/each}}
</ul>
Here is the output ...
<li>
<input id="activityTotal" class="ember-view ember-checkbox" type="checkbox" checked="checked">
<label data-bindattr-2689="2689">
<span></span>
</label>
<span>
<script id="metamorph-53-start" type="text/x-placeholder"></script>
Events
<script id="metamorph-53-end" type="text/x-placeholder"></script>
</span>
<script id="metamorph-54-start" type="text/x-placeholder"></script>
<script id="metamorph-54-end" type="text/x-placeholder"></script>
First of all you should wrap all this in a component.
You really should not be manually binding the id like this as ember uses it internally but I think it is acceptable in this case as I can't think of a better way but you need to maintain the uniqueness.
I would so something like this to ensure the id is unique and uses
checkBoxId: Ember.computed(function(){
return "checker-" + this.elementId;
}),
Here is the component's javascript file that will be executed when the component is ran:
App.XCheckboxComponent = Ember.Component.extend({
setup: Ember.on('init', function() {
this.on('change', this, this._updateElementValue);
}),
checkBoxId: Ember.computed(function(){
return "checker-" + this.elementId;
}),
_updateElementValue: function() {
this.sendAction();
return this.set('checked', this.$('input').prop('checked'));
}
});
Here is the component's template, I use unbound to bind the unique checkBoxId with the label's for:
<label for="{{unbound checkBoxId}}">
{{label}}
<input id="{{unbound checkBoxId}}" type="checkbox" {{bind-attr checked="checked"}}>
</label>
Here is how you might use it:
<ul>
{{#each contact in model}}
<li>{{x-checkbox label=contact.name enabled=contact.enabled}}</li>
{{/each}}
</ul>
And here is a working jsbin for ember 1.7.1 and here is a working jsbin for ember 1.11.1.
As of version 1.11, you don't need bind-attr. You should be able to bind the attribute like this:
<label for={{binding}}></label>
Code
<ul>
{% for item in lis %}
<li>
<div id="single-toggle">|Toggle|</div>
<div class="visible-when-folded">
<div class="name">{{ item.name }}</div>
<div class="date">{{ item.date }}</div>
</div>
<div class="invisible-when-folded">
<div class="about">{{ item.about }}</div>
<div class="contact_info">{{ item.contact_info }}</div>
</div>
</li>
{% endfor %}
</ul>
Example output code
|Toggle|
Peter
24-04-1990
A friendly guy
0474657434
|Toggle|
Martha
22-02-1984
An amazing gal
0478695675
|Toggle|
William
12-11-1974
An oldie
0478995675
Desired behavior
I would like that whenever you click on |Toggle| the about(e.g. A friendly guy)
and contact_info(e.g. 0474657434) part dissapear/reappear.
Attempt at solution
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded").toggle(); } );
});
But unfortunately this toggles the fields for each item in the list as opposed to only the one I click on.
Edit
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def toggle(request):
lis = [{'name':'Peter', 'date':'24-04-1990', 'about':'A friendly guy',
'contact_info':'0474657434' },
{'name':'Martha', 'date':'22-02-1984', 'about':'An amazing gal',
'contact_info':'0478695675' },
{'name':'William', 'date':'12-11-1974', 'about':'An oldie',
'contact_info':'0478995675' }]
return render_to_response('page.html', {'lis':lis},
context_instance=RequestContext(request))
You need to pass the current object as context in the selector to get the element related to event source object. You also need to use class instead of id or generate unique ids for div with id = single-toggle as html elements are supposed to have unique ids.
Live Demo
I have give the div with id a class="single-toggle"
Change
$("div.invisible-when-folded").toggle();
To
$("div.invisible-when-folded", this).toggle();
You code
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded", this).toggle(); } );
});
You need to focus the function on the div within the clicked div... The actual code you need to use is:
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded", this).toggle(); } );
});