jQuery Isotope Filtering Reset - select

I'm using JQuery Isotope with a combination, three-level filter. In all the examples I've come across, the only way to "reset" the filters is by clicking a "Show All" option.
Is it possible to "un-filter" results by clicking on a selected filter to un-select it?
Here is an example: http://jsfiddle.net/RevConcept/suagb/
Here is my code...
HTML
<div id="options" class="combo-filters">
<div class="option-combo location">
<ul class="filter option-set group level-one" data-filter-group="location">
<li class="hidden">any
<li>exterior
<li>interior
</ul>
</div>
<div class="option-combo illumination">
<ul class="filter option-set group level-two" data-filter-group="illumination">
<li class="hidden">any
<li>illuminated
<li>non-illuminated
</ul>
</div>
<div class="option-combo mount">
<ul class="filter option-set group level-three" data-filter-group="mount">
<li class="hidden">any
<li>wall
<li>ground
</ul>
</div>
</div><!--end options-->
CSS
header nav a {
color:#666666;
}
header nav a.selected {
color:#000000;
}
JAVASCRIPT
$(function(){
var $container = $('#container'),
filters = {};
$container.isotope({
itemSelector : '.project',
masonry: {
columnWidth: 80
}
});
// filter buttons
$('.filter a').click(function(){
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return;
}
var $optionSet = $this.parents('.option-set');
// change selected class
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
// store filter value in object
// i.e. filters.location = 'exterior'
var group = $optionSet.attr('data-filter-group');
filters[ group ] = $this.attr('data-filter-value');
// convert object into array
var isoFilters = [];
for ( var prop in filters ) {
isoFilters.push( filters[ prop ] )
}
var selector = isoFilters.join('');
$container.isotope({ filter: selector });
return false;
});
});

You could add a "Reload Page" button...
Here are 3 examples for you...
<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">
<input type="button" value="Reload Page" onClick="window.location.reload()">
<input type="button" value="Reload Page" onClick="history.go(0)">

isoSelective provides combining and toggling filters. Try using my updated version: https://github.com/simmerdesign/jquery-isoselective

Related

Make form dynamicly add input with number

can anyone make these functions simple?
i have a ul:
<ul class="phone-type">
<li class="office" id="1"></li>
<li class="mobile" id="2"></li>
<li class="fax" id="3"></li>
</ul>
and the JS :
var o = 0;var m = 0;var f = 0;
$('ul.phone-type li.office').click(function () {
o++;
$('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+o+'" name="phone['+$(this).attr('class')+'-'+o+']" type="text" ><br>');
});
$('ul.phone-type li.mobile').click(function () {
m++;
$('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+m+'" name="phone['+$(this).attr('class')+'-'+m+']" type="text" ><br>');
});
$('ul.phone-type li.fax').click(function () {
f++;
$('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+f+'" name="phone['+$(this).attr('class')+'-'+f+']" type="text" ><br>');
});
i have to reset it for every li..
is there any way that i can make it simple!!!!
tnx
This method will allow for an indefinite number of clickable list elements. Just ensure that you provide the 'data-type' attribute in any elements that are included.
When storing data in an html element, it is usually best to use the 'data' attribute. Using classes only works when there is one class.
HTML
<ul class="phone-type">
<li data-type="office" id="1">office</li>
<li data-type="mobile" id="2">mobile</li>
<li data-type="fax" id="3">fax</li>
</ul>
<div class="phones"></div>
JS
// This object will contain how many clicks each element has
var typeClicks = {};
$('ul.phone-type li').click(function() {
var li = $(this),
type = li.data('type'),
text = li.text(),
clicks;
// check if typeClicks contains any click data for this element
if (typeClicks.hasOwnProperty(type)) {
// if it does, increases tracked clicks by one
typeClicks[type]++;
clicks = typeClicks[type];
} else {
// if not, this will create an entry for this element
clicks = typeClicks[type] = 1;
}
// if not, this will create an entry for this element
$('.phones').append('<input class="form-control phone_type" placeholder="'+text+'-'+clicks+'" name="phone['+type+'-'+clicks+']" type="text" ><br>');
});

Modal: order of operations mirroring error with multiple modals

I have two different modals on the same page. they are each suppose to be separate modals with different content for the user to click on.
the problem is the top ends up mirroring the content of the bottom despite the difference in IDs.
Is there a method to override the order of operations? ...or is there specific JS that will differentiate the two from each other?
here is the quick version to see the problem: https://jsfiddle.net/anemnafair/Locnupay/2/
HTML
<body>
<button id="btn1"><img src="#" alt="image1"></button>
<div id="modal1" class="modal">
<div class="modal-content">
<span class="close"></span>
<div class="modal-body">
<p>Lorem ipsum.</p>
</div>
</div>
</div>
Second modal HTML
<button id="btn2"><img src="#" alt="image2"></button>
<div id="modal2" class="modal">
<div class="modal-content">
<span class="close"></span>
<div class="modal-body">
<p>Lorem ipsum.</p>
</div>
</div>
</div>
</body>
JS
var modal = document.getElementById('modal1');
var btn = document.getElementById("btn1");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
Second Modal JS
var modal = document.getElementById('modal2');
var btn = document.getElementById("btn2");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I got most of the code from W3- http://www.w3schools.com/howto/howto_css_modals.asp
Not sure if that helps any.
I need to get each modal acting separately instead of mimicking the other. That is the problem I have run out of clues of where to go next? I just need suggestions.

How to prevent multi triggers in bootstrap modal?

I have a confirm modal shown after a button clicked and in this modal has two buttons, "Cancel" and "Add". The "Add" will expend data into its own item list and it works fine. But if I click "Cancel" and then go back to show this modal again, if then I click "Add", my item list will be expended times depends on how many time I click "Cancel" before. I try .data("bs.modal", null) or .off('click') at .on("hidden.bs.modal"). None of them can fix my problem.
The sample link Sample
<div class="major">
<button class='btn btn-danger btn-xs' type="submit" name="additem" value="Add"><span class="fa fa-times"></span> add</button>
<ul id="itemlist" data="0">
</ul>
</div>
<div class="major">
<button class='btn btn-danger btn-xs' type="submit" name="additem" value="Add"><span class="fa fa-times"></span> add</button>
<ul id="itemlist" data="100">
</ul>
</div>
<!-- Modal -->
<div id="confirm" class="modal hide fade">
<div class="modal-body">
Are you sure?
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" id="add">Add</button>
<button type="button" data-dismiss="modal" class="btn">Cancel</button>
</div>
</div>
the script,
$('button[name="additem"]').on('click', function(e){
var $major=$(this).closest('.major');
e.preventDefault();
$('#confirm').modal({ backdrop: 'static', keyboard: false })
.one('click', '#add', function (e) {
var num = parseInt($major.children("#itemlist").attr("data")) + 1;
$major.children("#itemlist").append("<li>new item" + num + "</li>");
$major.children("#itemlist").attr("data", num);
});
});
$("#confirm").on("hidden.bs.modal", function(){
$(this).data("bs.modal", null);
$("#add").off("click");
});
Following were the problems :
Function for "Add Items"
All the code was inside function for Add Items, So whenever add button was getting called for displaying modal box, modal box's ADD button's code was also executing..
Jquery .one()
It will execute only one time, so I have replaced it with on which will be executed on every click to "Add button of Modal"
I have taken code out from the function and replaced one with on, now it works fine !!!
Updated fiddle can be found at : http://jsfiddle.net/L3ddq/732/
var $major ;
$('button[name="additem"]').on('click', function(e){
$major=$(this).closest('.major');
e.preventDefault();
$('#confirm').modal({ backdrop: 'static', keyboard: false });
});
$('#confirm').on('click', '#add', function (e) {
var num = parseInt($major.children("#itemlist").attr("data")) + 1;
$major.children("#itemlist").append("<li>new item" + num + "</li>");
$major.children("#itemlist").attr("data", num);
});

Ionic Return value navigation on different view

I have a form view with an input text. When I click on this input, another view is opened.
In this view, there are an input search and a list. The list change when I change a text from the input search.
I want when I click one item of the list, this view gets closed and the input text change. But I don't know how I can do that.
Can you help me please?
the input text in my form view:
<div class="select-typeevent">
<ion-item nav-clear menu-close ui-sref="menu.setlocation">
<label class="padding">
Address:
</label>
</ion-item>
</div>
My searchview:
<ion-view view-title="Address" class="content">
<ion-content>
<h1>Address</h1>
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input class="border-none" name="txtssearch" type="search" placeholder="Search" ng-model="addresssearch" ng-change="getGeocode(addresssearch)">
</label>
<button class="button button-clear" ng-click="addresssearch='';getGeocode(addresssearch)">
Annuler
</button>
</div>
<div class="list" >
<a ng-repeat="addr in addresslist" class="item" ng-click="setaddress(addr)">
{{addr.address}} {{addr.location}}
</a>
</div>
</ion-content>
</ion-view>
And the js:
'Use Strict';
angular.module('App').controller('setlocationController', function ($scope,$state, $cordovaOauth, $localStorage, $location, $http, $ionicPopup,$firebaseObject,$ionicHistory, Auth, FURL, Utils) {
$scope.getGeocode = function (addresssearch) {
$scope.geodata = {};
$scope.queryResults = {};
$scope.queryError = {};
$http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + addresssearch)
.then(function (_results) {
$scope.addresslist = [];
$scope.queryResults = _results.data.results;
console.log($scope.queryResults);
$scope.queryResults.forEach(function(result) {
$scope.addresslist.push({ 'address': result.formatted_address, 'location': result.geometry.location });
});
},
function error(_error){
$scope.queryError = _error;
})
};
// Here I want when I click one item of the list, this view gets closed and the input text of formview change.
$scope.setaddress = function (addr) {
$scope.setaddress = addr;
$ionicHistory.backView();
}
Why not using an $ionicModal:
$scope.getGeocode = function (addresssearch) {
...
$scope.modal.show();
}
Previously set the modal:
$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
Where my-modal.html points to the template which shows geocode information.

Handle radio button form in Marionette js

I'm trying to construct a view in my app that will pop up polling questions in a modal dialog region. Maybe something like this for example:
What is your favorite color?
>Red
>Blue
>Green
>Yellow
>Other
Submit Vote
I've read that Marionette js doesn't support forms out of the box and that you are advised to handle on your own.
That structure above, branch and leaves (question and list of options), suggests CompositeView to me. Is that correct?
How do I trigger a model.save() to record the selection? An html form wants an action. I'm unclear on how to connect the form action to model.save().
My rough draft ItemView and CompositeView code is below. Am I in the ballpark? How should it be adjusted?
var PollOptionItemView = Marionette.ItemView.extend({
template: Handlebars.compile(
'<input type="radio" name="group{{pollNum}}" value="{{option}}">{{option}}<br>'
)
});
var PollOptionsListView = Marionette.CompositeView.extend({
template: Handlebars.compile(
//The question part
'<div id="poll">' +
'<div>{{question}}</div>' +
'</div>' +
//The list of options part
'<form name="pollQuestion" action="? what goes here ?">' +
'<div id="poll-options">' +
'</div>' +
'<input type="submit" value="Submit your vote">' +
'</form>'
),
itemView: PollOptionItemView,
appendHtml: function (compositeView, itemView, index) {
var childrenContainer = $(compositeView.$("#poll-options") || compositeView.el);
var children = childrenContainer.children();
if (children.size() === index) {
childrenContainer.append(itemView.el);
} else {
childrenContainer.children().eq(index).before(itemView.el);
}
}
});
MORE DETAILS:
My goal really is to build poll questions dynamically, meaning the questions and options are not known at runtime but rather are queried from a SQL database thereafter. If you were looking at my app I'd launch a poll on your screen via SignalR. In essence I'm telling your browser "hey, go get the contents of poll question #1 from the database and display them". My thought was that CompositeViews are best suited for this because they are data driven. The questions and corresponding options could be stored models and collections the CompositeView template could render them dynamically on demand. I have most of this wired and it looks good. My only issue seems to be the notion of what kind of template to render. A form? Or should my template just plop some radio buttons on the screen with a submit button below it and I write some javascript to try to determine what selection the user made? I'd like not to use a form at all and just use the backbone framework to handle the submission. That seems clean to me but perhaps not possible or wise? Not sure yet.
I'd use the following approach:
Create a collection of your survey questions
Create special itemviews for each type of question
In your CompositeView, choose the model itemView based on its type
Use a simple validation to see if all questions have been answered
Output an array of all questions and their results.
For an example implementation, see this fiddle: http://jsfiddle.net/Cardiff/QRdhT/
Fullscreen: http://jsfiddle.net/Cardiff/QRdhT/embedded/result/
Note:
Try it without answering all questions to see the validation at work
Check your console on success to view the results
The code
// Define data
var surveyData = [{
id: 1,
type: 'multiplechoice',
question: 'What color do you like?',
options: ["Red", "Green", "Insanely blue", "Yellow?"],
result: null,
validationmsg: "Please choose a color."
}, {
id: 2,
type: 'openquestion',
question: 'What food do you like?',
options: null,
result: null,
validationmsg: "Please explain what food you like."
}, {
id: 3,
type: 'checkbox',
question: 'What movie genres do you prefer?',
options: ["Comedy", "Action", "Awesome", "Adventure", "1D"],
result: null,
validationmsg: "Please choose at least one movie genre."
}];
// Setup models
var questionModel = Backbone.Model.extend({
defaults: {
type: null,
question: "",
options: null,
result: null,
validationmsg: "Please fill in this question."
},
validate: function () {
// Check if a result has been set, if not, invalidate
if (!this.get('result')) {
return false;
}
return true;
}
});
// Setup collection
var surveyCollection = Backbone.Collection.extend({
model: questionModel
});
var surveyCollectionInstance = new surveyCollection(surveyData);
console.log(surveyCollectionInstance);
// Define the ItemViews
/// Base itemView
var baseSurveyItemView = Marionette.ItemView.extend({
ui: {
warningmsg: '.warningmsg',
panel: '.panel'
},
events: {
'change': 'storeResult'
},
modelEvents: {
'showInvalidMessage': 'showInvalidMessage',
'hideInvalidMessage': 'hideInvalidMessage'
},
showInvalidMessage: function() {
// Show message
this.ui.warningmsg.show();
// Add warning class
this.ui.panel.addClass('panel-warningborder');
},
hideInvalidMessage: function() {
// Hide message
this.ui.warningmsg.hide();
// Remove warning class
this.ui.panel.removeClass('panel-warningborder');
}
});
/// Specific views
var multipleChoiceItemView = baseSurveyItemView.extend({
template: "#view-multiplechoice",
storeResult: function() {
var value = this.$el.find("input[type='radio']:checked").val();
this.model.set('result', value);
}
});
var openQuestionItemView = baseSurveyItemView.extend({
template: "#view-openquestion",
storeResult: function() {
var value = this.$el.find("textarea").val();
this.model.set('result', value);
}
});
var checkBoxItemView = baseSurveyItemView.extend({
template: "#view-checkbox",
storeResult: function() {
var value = $("input[type='checkbox']:checked").map(function(){
return $(this).val();
}).get();
this.model.set('result', (_.isEmpty(value)) ? null : value);
}
});
// Define a CompositeView
var surveyCompositeView = Marionette.CompositeView.extend({
template: "#survey",
ui: {
submitbutton: '.btn-primary'
},
events: {
'click #ui.submitbutton': 'submitSurvey'
},
itemViewContainer: ".questions",
itemViews: {
multiplechoice: multipleChoiceItemView,
openquestion: openQuestionItemView,
checkbox: checkBoxItemView
},
getItemView: function (item) {
// Get the view key for this item
var viewId = item.get('type');
// Get all defined views for this CompositeView
var itemViewObject = Marionette.getOption(this, "itemViews");
// Get correct view using given key
var itemView = itemViewObject[viewId];
if (!itemView) {
throwError("An `itemView` must be specified", "NoItemViewError");
}
return itemView;
},
submitSurvey: function() {
// Check if there are errors
var hasErrors = false;
_.each(this.collection.models, function(m) {
// Validate model
var modelValid = m.validate();
// If it's invalid, trigger event on model
if (!modelValid) {
m.trigger('showInvalidMessage');
hasErrors = true;
}
else {
m.trigger('hideInvalidMessage');
}
});
// Check to see if it has errors, if so, raise message, otherwise output.
if (hasErrors) {
alert('You haven\'t answered all questions yet, please check.');
}
else {
// No errors, parse results and log to console
var surveyResult = _.map(this.collection.models, function(m) {
return {
id: m.get('id'),
result: m.get('result')
}
});
// Log to console
alert('Success! Check your console for the results');
console.log(surveyResult);
// Close the survey view
rm.get('container').close();
}
}
});
// Create a region
var rm = new Marionette.RegionManager();
rm.addRegion("container", "#container");
// Create instance of composite view
var movieCompViewInstance = new surveyCompositeView({
collection: surveyCollectionInstance
});
// Show the survey
rm.get('container').show(movieCompViewInstance);
Templates
<script type="text/html" id="survey">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" > A cool survey regarding your life </h3>
</div>
<div class="panel-body">
<div class="questions"></div>
<div class="submitbutton">
<button type="button" class="btn btn-primary">Submit survey!</button>
</div>
</div>
</div >
</script>
<script type="text/template" id="view-multiplechoice">
<div class="panel panel-success">
<div class="panel-heading">
<h4 class="panel-title" > <%= question %> </h4>
</div>
<div class="panel-body">
<div class="warningmsg"><%= validationmsg %></div>
<% _.each( options, function( option, index ){ %>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="<%= index %>" value="<%= option %>"> <%= option %>
</label>
</div>
<% }); %>
</div>
</div>
</script>
<script type="text/template" id="view-openquestion">
<div class="panel panel-success">
<div class="panel-heading">
<h4 class="panel-title" > <%= question %> </h4>
</div>
<div class="panel-body">
<div class="warningmsg"><%= validationmsg %></div>
<textarea class="form-control" rows="3"></textarea>
</div>
</div >
</script>
<script type="text/template" id="view-checkbox">
<div class="panel panel-success">
<div class="panel-heading">
<h4 class="panel-title" > <%= question %> </h4>
</div>
<div class="panel-body">
<div class="warningmsg"><%= validationmsg %></div>
<% _.each( options, function( option, index ){ %>
<div class="checkbox">
<label>
<input type="checkbox" value="<%= option %>"> <%= option %>
</label>
</div>
<% }); %>
</div>
</div>
</script>
<div id="container"></div>
Update: Added handlebars example
Jsfiddle using handlebars: http://jsfiddle.net/Cardiff/YrEP8/