Hiding values ​with jQuery - javascript

I'm having trouble hiding data with jQuery.
I have several products and a filtering system in jQuery, I would like to hide filters that are not used on a given subpage, in my case, data-power.
I am extracting data that matches .product data-power, but now I don't know how to hide a value that is not listed in my 1200 case. Example:
$('.stat').on('click', function() {
var $stats = $('.stat:checked');
var $items = $('.list .product');
$items.show();
if ($stats.length == 0)
return;
var $vstats = $.map($stats, function(o) {
return $(o).data('id');
});
$stats.each(function() {
var $stat = $(this);
$items.filter(function() {
var $currentitem = $(this).data($stat.data('type'));
if ($currentitem.toString().indexOf(",") > -1) {
var $item = $currentitem.split(",");
var hit = 0;
$item.forEach(function(m) {
if ($vstats.indexOf(m) > -1) {
hit++;
}
});
if (hit > 0) {
return false;
} else {
return true;
}
} else {
if ($vstats.indexOf($currentitem) > -1) {
return false;
} else {
return true;
}
}
}).hide();
})
});
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
var array = [];
$('.product').each(function(i, e) {
array.push($(e).data('power'));
});
var unique = array.filter(onlyUnique);
unique.sort();
alert(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="power">
<h2>power</h2>
<div class="checkbox">
<label>
<input data-id="750" data-type="power" class="stat power" type="checkbox">750 </label>
<label>
<input data-id="800" data-type="power" class="stat power" type="checkbox">800 </label>
<label>
<input data-id="1200" data-type="power" class="stat power" type="checkbox">1200 </label>
</div>
</div>
<div class="grill">
<h2>grill</h2>
<div class="checkbox">
<label>
<input data-id="yes" data-type="grill" class="stat grill" type="checkbox">yes </label>
<label>
<input data-id="no" data-type="grill" class="stat grill" type="checkbox">no </label>
</div>
</div>
<div class="list">
<div class="col-6 col-lg-3 product" data-power="750" data-grill="yes">
<a href="/href/freh">
<div class="product-page__container product-container text-center">
<div class="product-page__name">
<h2><span class="d-block">Product Name</span> Product 1</h2>
</div>
</div>
</a>
</div>
<div class="col-6 col-lg-3 product" data-power="800" data-grill="yes">
<a href="/href/freh">
<div class="product-page__container product-container text-center">
<div class="product-page__name">
<h2><span class="d-block">Product Name 2</span> Product 2</h2>
</div>
</div>
</a>
</div>
</div>
https://jsfiddle.net/x0atpcz4/1/

I would select the items you are to filter and grab the values. Then I would grab the filters and see if they exists and remove the ones that do not.
var powers = $('[data-power]').map(function (){ return this.dataset.power; }).get();
$('[data-id]').filter(function () {
return !powers.includes(this.dataset.id)
}).closest("label").hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="power">
<h2>power</h2>
<div class="checkbox">
<label>
<input data-id="750" data-type="power" class="stat power" type="checkbox">750 </label>
<label>
<input data-id="800" data-type="power" class="stat power" type="checkbox">800 </label>
<label>
<input data-id="1200" data-type="power" class="stat power" type="checkbox">1200 </label>
</div>
</div>
<div class="list">
<div class="col-6 col-lg-3 product" data-power="750">
<a href="/href/freh">
<div class="product-page__container product-container text-center">
<div class="product-page__name">
<h2><span class="d-block">Product Name</span> Product 1</h2>
</div>
</div>
</a>
</div>
<div class="col-6 col-lg-3 product" data-power="800">
<a href="/href/freh">
<div class="product-page__container product-container text-center">
<div class="product-page__name">
<h2><span class="d-block">Product Name 2</span> Product 2</h2>
</div>
</div>
</a>
</div>
</div>

Related

After checkbox filter is toggled, search filter no longer works

Please see the issue in action, here: https://streamable.com/n6np71
The issue is secluded to this area of code:
// check "Show all" on page load
$('#menu-checkbox-filters-all').prop('checked', true);
$(".filters input:not(#menu-checkbox-filters-all)").prop("checked", false);
var $checkboxes = $('.filters input');
$checkboxes.change(function(event){
let currentTarget = event.currentTarget;
// if all is selected, deselect others
if (currentTarget.id == "menu-checkbox-filters-all")
$(".filters input:not(#menu-checkbox-filters-all)").prop("checked", false);
else // remove the checked prop from all
$("#menu-checkbox-filters-all").prop("checked",false);
// if none is checked anymore, check all
if (!$checkboxes.filter(":checked").length)
$("#menu-checkbox-filters-all").prop("checked", true)
var filters = [];
// get checked checkboxes values
$checkboxes.filter(':checked').each(function(){
filters.push( this.value );
$grid.isotope();
});
filters = filters.join(', ');
$contentContainer.isotope({ filter: filters });
});
<div class="filter-menu">
<div class="menu-headers-section">
<div class="menu-tag"></div>
<div class="menu-language-checklist">
<h3 class="menu-heading">Language</h3>
</div>
<div class="menu-captions-checklist">
<h3 class="menu-heading">Captions</h3>
</div>
</div>
<div class="menu-content-section">
<div class="menu-tag">
<div class="list-content-section list-section-language-tags">
<div class="list-language-tag tag-language-all"><img class="icon-flag" src="/ASSETS/icon-star.svg" alt="">All</div>
</div>
</div>
<div class="menu-language-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value="*" id="menu-checkbox-filters-all">
<span class="checkmark"></span>
</label>
</div>
</div>
<div class="menu-content-section">
<div class="menu-tag">
<div class="list-content-section list-section-language-tags">
<div class="list-language-tag tag-language-irish"><img class="icon-flag" src="/ASSETS/icon-flag-ireland.svg" alt="">Irish</div>
</div>
</div>
<div class="menu-language-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".language-irish" id="language-irish">
<span class="checkmark"></span>
</label>
</div>
<div class="menu-captions-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".captions-irish" id="captions-irish" test-value="AAA">
<span class="checkmark"></span>
</label>
</div>
</div>
<div class="menu-content-section">
<div class="menu-tag">
<div class="list-content-section list-section-language-tags">
<div class="list-language-tag tag-language-korean"><img class="icon-flag" src="/ASSETS/icon-flag-south-korea.svg" alt="">Korean</div>
</div>
</div>
<div class="menu-language-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".language-korean" id="language-korean">
<span class="checkmark"></span>
</label>
</div>
<div class="menu-captions-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".captions-korean" id="captions-korean">
<span class="checkmark"></span>
</label>
</div>
</div>
<div class="menu-content-section">
<div class="menu-tag">
<div class="list-content-section list-section-language-tags">
<div class="list-language-tag tag-language-estonian"><img class="icon-flag" src="/ASSETS/icon-flag-estonia.svg" alt="">Estonian</div>
</div>
</div>
<div class="menu-language-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".language-estonian" id="language-estonian">
<span class="checkmark"></span>
</label>
</div>
<div class="menu-captions-checklist filters">
<label class="checklist-container">
<input class="menu-checkbox" type="checkbox" value=".captions-estonian" id="captions-estonian">
<span class="checkmark"></span>
</label>
</div>
</div>
</div>
</div>
To see full code, please view this:
https://codepen.io/sahilsignup/pen/oNMQJbq
Ideally, even after toggling a filter via the menu (i.e., whether there is a filter active or not), the search bar/filter should work.
Kindly note that Isotope is being used for filtering.
(Sorry for the outdated jQuery — essentially no knowledge of JS/jQuery, so this was taken from Codepen. The HTML has not yet been organized.)
Thank you!

jquery.repeater with bootstrap custom-switch failure

Good Evening,
I have a problem with the jquery form repeater plugin and bootstrap.
I have this form element witch is part of the repeater form:
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="questionSwitch" name="question_correct[]">
<label class="custom-control-label" for="questionSwitch">Richtige Antwort</label>
</div>
Now is the problem if the repeater repeat this element and I click on the second or third repeated item on the switch the switch on the first item get changed not the one I clicked. Because they all three have the same id.
Does anyone have an idea how to fix this? Its the first time working with the form repeater.
Here is a bit more of the Code
$(function () {
'use strict';
if (!$('#multiple-choice').attr('checked')) {
$('#questions').hide();
}
$('#multiple-choice').on('click', function () {
if (this.checked)
$('#questions').show();
else $('#questions').hide();
});
// form repeater jquery
$('#whitelist-new-question').repeater({
show: function () {
$(this).slideDown();
// Feather Icons
if (feather) {
feather.replace({ width: 14, height: 14 });
}
},
hide: function (deleteElement) {
if (confirm('Möchten Sie diese Antwort wirklich löschen?')) {
$(this).slideUp(deleteElement);
}
}
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.1.2/jquery.repeater.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.28.0/feather.min.js"></script>
<div class="card">
<div class="card-body">
<form class="form form-vertical" action="{{ route('whitelist-new-question') }}" method="post"
id="whitelist-new-question">
<div class="row">
#csrf
<div class="col-12">
<div class="form-group">
<label for="question-title">Titel</label>
<input type="text" class="form-control" id="question-title" name="questionTitle"
value="{{ old('questionTitle') }}" />
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="question-required"
name="questionRequired" value="1"
{{ old('questionRequired') == '1' ? 'checked' : '' }}>
<label class="custom-control-label" for="question-required">Immer Fragen</label>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="multiple-choice" name="multiChoice"
value="1" {{ old('multiChoice') == '1' ? 'checked' : '' }}>
<label class="custom-control-label" for="multiple-choice">Multiple Choice</label>
</div>
</div>
</div>
<div class="col-12" id="questions">
Antworten
<hr />
<div data-repeater-list="questions">
<div data-repeater-item>
<div class="row d-flex align-items-end">
<div class="col-md-4 col-12">
<div class="form-group">
<label for="question-text">Text</label>
<input type="text" class="form-control" id="question-text"
name="question_text[]" aria-describedby="question-text" />
</div>
</div>
<div class="col-md-2 col-12 mt-auto mb-auto">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="currect-switch"
name="question_correct[]">
<label class="custom-control-label" for="currect-switch">Richtige
Antwort</label>
</div>
</div>
<div class="col-md-2 col-12 mb-50">
<div class="form-group">
<button class="btn btn-outline-danger text-nowrap px-1" data-repeater-delete
type="button">
<i data-feather="x" class="mr-25"></i>
<span>Löschen</span>
</button>
</div>
</div>
</div>
<hr />
</div>
</div>
<div class="row">
<div class="col-12">
<button class="btn btn-icon btn-primary" type="button" data-repeater-create>
<i data-feather="plus" class="mr-25"></i>
<span>Weitere Antwort</span>
</button>
</div>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-success mt-2">Speichern</button>
</div>
</div>
</form></div></div>
Ok i got a fix for that.
in the js script i created a variable number and added this code in the show event of the repeater:
show: function () {
var inputSwitch = $(this).find('.custom-control-input');
var labelSwitch = $(this).find('.custom-control-label');
var id = 'currect-switch-' + number;
inputSwitch.attr("id", id);
labelSwitch.attr("for", id);
$(this).slideDown();
// Feather Icons
if (feather) {
feather.replace({ width: 14, height: 14 });
}
number++;
},

Remove appended data on second click

I have few checkboxes. When I click on any of them I pass the value to span. Everything seems to work fine but there's something that I can't resolve. When I click first time value is passed to my span (checkbox is checked) but when I unclick this checkbox, value is passing to span again instead of delete it from my span. Next thing, when I want to write my own text I have other checkbox for that. When I click on it I see input. I cant write text and it will be appended to my span. I want to remove this value too when I unclick this checkbox. Last thing, I want to add red border to empty elements. Anyone could help me?
$('.checkbox').on('click', function(){
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
check whether the event is fired when the checkbox is checked or not checked.
$('.checkbox').on('click', function(){
if($(this).is(':checked')){
//do you logic when the checkbox is checked.
}else{
//do your logic when the checkbox is not checked.
}
});
You need to loop over all checkboxes when each checkbox is clicked
Note I wrapped the whole thing in the label.
$('.component-other-value, .fruits').on('change', function() {
var fruits = [], other = [];
$('.component-other-value, .fruits').each(function() {
if (this.checked) {
var dataName = $(this).attr('data-product');
var value = $(this).val();
if (dataName) other.push(value)
else fruits.push(value)
}
});
$('#summary_fruits').text(fruits.join(","));
$('#summary_other_fruits').text(other.join(","));
});
$('.component-other').on('click', function() {
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<img src="img/ananas.png">
<p class="description">Ananas</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<img src="img/jablko.png">
<p class="description">Jabłko</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<img src="img/owoce-wlasne.png">
<p class="description">Własna propozycja</p>
</label>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<img src="img/owoce-brak.png">
<p class="description">Bez owoców</p>
</label>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
$('.checkbox').on('click', function(){
var check = $(this);//PROPERTIES OF CLICKED CHECKBOX
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
if (check.prop('checked')==true){ // check weather checkbox is checked.
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
}
else { //if not remove the occurence of value that you unchecked
str = $('#summary_' + dataAttr).html();
$('#summary_' + dataAttr).html(str.replace(dataAttrVal+", ",""));
}
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>

knockout js, add additional elements to an array

I have an app where I want to add extra elements to an item in an array, I have created a fiddle of what I'm trying to achieve.
So the user starts the app, they click next fill in some details of an item and a description, they then should click next and fill in a price for the item(this is where I'm stuck). This example works up to a point, as in whenever I try and implement the price part I seem to be getting it wrong. You'll see once I click next the item is added to the array, however how do add more elements to the current item in the array. In case I've not made sense the logic should be:
Start
Page one (enter name and description)
Page two (enter price)
I understand I could do this all on one page but I don't want to I want knockout to be able to add a price after the name and description page. I would also like to be able to go back and amend the item. Can you anybody help in seeing what I should be doing next?
When I insert the name and description, do I have to also make an empty element in the array for the price? Then once the price is entered somehow insert this into the price element in the array? Not sure how/if this should be implemented.
This is my first knockout app so I be surprised if what I've actually done is correct, any help or pointers gratefully received :)
My code is below:
$(function() {
var main = new stuff();
ko.applyBindings(main, $('#ko')[0]);
});
function Item(data) {
this.itemname = ko.observable(data.itemname);
this.itemdescription = ko.observable(data.itemdescription);
this.itemenabled = ko.observable(data.itemenabled);
}
function stuff() {
var self = this;
self.items = ko.observableArray([]);
self.newItemName = ko.observable();
self.newItemDescription = ko.observable();
self.newItemEnabled = ko.observable();
// Operations
self.addItem = function() {
self.items.push(new Item({
itemname: this.newItemName(),
itemdescription: this.newItemDescription(),
itemenabled: this.newItemEnabled()
}));
};
};
//jquery stuff
$('#start').on('click', function(e) {
$("#page1").show(500);
$('#panel1').css('visibility', 'visible').hide().fadeIn().removeClass('hidden');
$("#start").hide(500);
})
$('#back').on('click', function(e) {
$("#panel1").hide(500);
$("#page1").hide(500);
$("#start").show(500);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="submit" class="btn btn-primary" id="start">Start</button>
<div id="ko">
<div class="panel panel-default hidden" id="panel1">
<div id="page1">
<form data-bind="submit: addItem">
<div class="panel panel-default" style="padding: 15px 0px 0px 0px;" id="panel2">
<div class="container">
<div class="form-group row">
<label for="inputItemName" class="col-lg-3 col-form-label">Enter Item Name</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputItemName" data-bind="value: newItemName" placeholder="">
</div>
</div>
<div class="form-group row">
<label for="textareaItemDescription" class="col-lg-3 col-form-label">Enter Item Description</label>
<div class="col-lg-8">
<textarea class="form-control" id="textareaItemDescription" rows="3" data-bind="value: newItemDescription"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-3 col-sm-9">
<label class="custom-control custom-checkbox checkbox-inline no_indent" style="font-weight:bold;">
<input type="checkbox" class="custom-control-input" checked="checked" data-bind="checked: newItemEnabled">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" style="padding-bottom: 2px;">Enabled</span>
</label>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-primary" id="back">Back</button>
<div class="pull-right">
<button type="submit" class="btn btn-primary" id="next1">Next</button>
</div>
</form>
</div>
</div>
<ul data-bind="foreach: items, visible: items().length > 0">
<li>
<input data-bind="value: itemname" style="color: black;" />
</li>
<li>
<input data-bind="value: itemdescription" style="color: black;" />
</li>
<li>
<input type="checkbox" data-bind="checked: itemenabled" />
</li>
</ul>
</div>
Ok, so I have added a new observable to track the page number along with basic functions to increment/decrement the number then I simply add the new item after the price has also been added.
$(function() {
var main = new stuff();
ko.applyBindings(main, $('#ko')[0]);
});
function Item(data) {
this.itemname = ko.observable(data.itemname);
this.itemdescription = ko.observable(data.itemdescription);
this.itemenabled = ko.observable(data.itemenabled);
this.price = ko.observable(data.itemprice);
}
function stuff() {
var self = this;
self.items = ko.observableArray([]);
self.newItemName = ko.observable();
self.newItemDescription = ko.observable();
self.newItemEnabled = ko.observable();
self.newItemPrice = ko.observable();
self.page = ko.observable(1);
// Operations
self.next = function() {
if (self.page() === 2) {
self.addItem();
}
self.page(self.page() + 1)
}
self.back = function() {
if (self.page() == 1) {
$("#panel1").hide(500);
$("#page1").hide(500);
$("#start").show(500);
}
self.page(self.page() - 1);
}
self.addItem = function() {
self.items.push(new Item({
itemname: this.newItemName(),
itemdescription: this.newItemDescription(),
itemenabled: this.newItemEnabled(),
itemprice: this.newItemPrice(),
}));
};
};
//jquery stuff
$('#start').on('click', function(e) {
$("#page1").show(500);
$('#panel1').css('visibility', 'visible').hide().fadeIn().removeClass('hidden');
$("#start").hide(500);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="submit" class="btn btn-primary" id="start">Start</button>
<div id="ko">
<div class="panel panel-default hidden" id="panel1">
<div id="page1">
<form data-bind="submit: next">
<div class="panel panel-default" style="padding: 15px 0px 0px 0px;" id="panel2">
<div class="container" data-bind="if: page() == 1">
<div class="form-group row">
<label for="inputItemName" class="col-lg-3 col-form-label">Enter Item Name</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputItemName" data-bind="value: newItemName" placeholder="">
</div>
</div>
<div class="form-group row">
<label for="textareaItemDescription" class="col-lg-3 col-form-label">Enter Item Description</label>
<div class="col-lg-8">
<textarea class="form-control" id="textareaItemDescription" rows="3" data-bind="value: newItemDescription"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-3 col-sm-9">
<label class="custom-control custom-checkbox checkbox-inline no_indent" style="font-weight:bold;">
<input type="checkbox" class="custom-control-input" checked="checked" data-bind="checked: newItemEnabled">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" style="padding-bottom: 2px;">Enabled</span>
</label>
</div>
</div>
</div>
</div>
<div class="container" data-bind="if: page() == 2">
<div class="form-group row">
<label for="inputPrice" class="col-lg-3 col-form-label">Enter Price</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputPrice" data-bind="value: newItemPrice" placeholder="">
</div>
</div>
</div>
<button type="button" data-bind="click: back" class="btn btn-primary" id="back">Back</button>
<div class="pull-right">
<button type="submit" class="btn btn-primary" id="next1">Next</button>
</div>
</form>
</div>
</div>
<ul data-bind="foreach: items, visible: items().length > 0">
<li>
<input data-bind="value: itemname" style="color: black;" />
</li>
<li>
<input data-bind="value: itemdescription" style="color: black;" />
</li>
<li>
<label for="price">Price</label>
<input id="price" data-bind="value: price" style="color: black;" />
</li>
<li>
<input type="checkbox" data-bind="checked: itemenabled" />
</li>
</ul>
</div>

Setting a variable limit on checkbox selection

I am attempting to set a variable limit on how many checkboxes can be set, based on a previous selection.
In my code I have an option input, where you select your choice (which is the templates and limitTemplate variables). Then I have some checkbox inputs. Let's say I chose my the option for 2 cards. Then I want to choose two checkboxes below it and then not be able to choose any additional cards.
For some reason my code is saying I am reaching the limit on my first selection, regardless of the card limit option. As you can see in my #template-number (where is says "Choose x templates from below") that I am getting the limitTemplate to work, at least at that point.
Does anyone see what I am doing wrong?
The part of the code where I am trying to restrict the limit is here:
if ($(templateCount >= limitTemplate)) {
event.preventDefault();
$('.tp-template-check[type="checkbox"]').not(':checked').prop('disabled', true);
alert("You reached your limit");
}
ps - it looks like a lot of HTML, but it is basically checkbox inputs.
Here is a fiddle in case you prefer this method.
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#tp-frequency').on('change', function() {
var templates = $('#tp-frequency option:selected').val();
$('#template-number').html(templates);
// Setting limit for TP templates
$('.tp-template-check').on('change', function() {
var limitTemplate = templates;
if (!this.checked || $('.tp-template-check:checked').length <= limitTemplate) {
$(this).parents('.product-wrap:first').find('.checkmark-img').fadeBoolToggle(this.checked);
var templateCount = $('.tp-template-check:checked').length;
if ($(templateCount > 0)) {
$('#templateCount').html(templateCount + " Template" + (templateCount == 1 ? "" : "s") + " Selected");
}
if ($(templateCount >= limitTemplate)) {
event.preventDefault();
$('.tp-template-check[type="checkbox"]').not(':checked').prop('disabled', true);
alert("You reached your limit");
}
if (templateCount == limitTemplate) {
$('#templateCountComplete').fadeBoolToggle($('.tp-template-check:checked').length == limitTemplate).addClass('block');
} else if (templateCount > limitTemplate) {
$('.tp-template:checkbox').attr('checked', false);
$('#templateCountComplete').hide();
}
} else {
$('#templateCountComplete').hide();
}
}); //End of .tp-template-check func
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2 class="section-subtitle">Choose the limit</h2>
<p class="small-description margin25">* Some choices result in more/less cards.</p>
<select id="tp-frequency" class="option-input">
<option value='' disabled selected>Please choose option</option>
<option value='5'>5 cards</option>
<option value='3'>3 cards</option>
<option value='2'>2 cards</option>
</select>
<div id="tp-template-section">
<!-- Template Section -->
<h2 class="section-subtitle">Choose <span id="template-number"></span> templates from below.</h2>
<p id="test2"></p>
<p id="templateCount"></p>
<div id="templateCountComplete"><img src="images/checkmark.png" alt="Template Selection Complete" id="templateCountImg"></div>
<div id="tp-template-wrap">
<div class="tp-template">
<div class="product-wrap">
<label for="tp-winter" class="package-check-toggle">
<h4 class="tp-template-title">Winter</h4>
<img src="images/tp-winter.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Winter" data-template-image="<img src='images/tp-winter.png' class='review-img'>" id="tp-winter" value="Winter">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-spring" class="package-check-toggle">
<h4 class="tp-template-title">Spring</h4>
<img src="images/tp-spring.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Spring" data-template-image="<img src='images/tp-spring.png' class='review-img'>" id="tp-spring" value="Spring">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-summer" class="package-check-toggle">
<h4 class="tp-template-title">Summer</h4>
<img src="images/tp-summer.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Summer" data-template-image="<img src='images/tp-summer.png' class='review-img'>" id="tp-summer" value="Summer">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-fall" class="package-check-toggle">
<h4 class="tp-template-title">Fall</h4>
<img src="images/tp-fall.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Fall" data-template-image="<img src='images/tp-fall.png' class='review-img'>" id="tp-fall" value="Fall">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-newYears" class="package-check-toggle">
<h4 class="tp-template-title">New Years</h4>
<img src="images/tp-newYears.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="New Years" data-template-image="<img src='images/tp-newYears.png' class='review-img'>" id="tp-newYears" value="New Years">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-independence" class="package-check-toggle">
<h4 class="tp-template-title">Independence Day</h4>
<img src="images/tp-independence.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Independence Day" data-template-image="<img src='images/tp-independence.png' class='review-img'>" id="tp-independence" value="Independence Day">
</div>
</div>
<div class="tp-template">
<div class="product-wrap">
<label for="tp-thanksgiving" class="package-check-toggle">
<h4 class="tp-template-title">Thanksgiving</h4>
<img src="images/tp-thanksgiving.png" class="tp-template-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="tp-template-check" data-template="Thanksgiving" data-template-image="<img src='images/tp-thanksgiving.png' class='review-img'>" id="tp-thanksgiving" value="Thanksgiving">
</div>
</div>
Some of your if statement conditions seem to be incorrect. You encased the conditions like they were jQuery selectors.
Change this:
if ($(templateCount > 0)) {
...
}
if ($(templateCount >= limitTemplate)) {
...
}
To this:
if (templateCount > 0) {
...
}
if (templateCount >= limitTemplate) {
...
}

Categories