Show all divs on Unchecking the checkboxes - javascript

I have a code for product list in different divs based on different data attributes like data-brand,data-store and some more. I am filtering the records with checkbox selection which my friend helped me to develop.I need small change in this.Look at the code.
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div>
<div class="content"
data-category="shoes"
data-price="4000"
data-size="38"
data-brand="Nike">
<img src="http://placehold.it/120x80">
<p>Nike 38<br>$4000</p>
</div>
<div class="content"
data-category="shirts"
data-price="6000"
data-size="20"
data-brand="Nike">
<img src="http://placehold.it/140x80">
<p>Nike 20<br>$6000</p>
</div>
<div class="content"
data-category="shoes"
data-price="500"
data-size="20"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 20<br>$500</p>
</div>
<div class="content"
data-category="shoes"
data-price="780"
data-size="42"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 42<br>$780</p>
</div>
<div class="content"
data-category="shirts"
data-price="1200"
data-size="40"
data-brand="Sunbaby">
<img src="http://placehold.it/140x80">
<p>Sunbaby 40<br>$1200</p>
</div>
<div class="content"
data-category="shoes"
data-price="2000"
data-size="70"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 70<br>$2000</p>
</div>
<div class="content"
data-category="shoes"
data-price="800"
data-size="50"
data-brand="Sunbaby">
<img src="http://placehold.it/120x80">
<p>Sunbaby 50<br>$800</p>
</div>
<div class="content"
data-category="shirts"
data-price="1300"
data-size="20"
data-brand="Nike">
<img src="http://placehold.it/140x80">
<p>Nike 20<br>$1300</p>
</div>
<div class="content"
data-category="shirts"
data-price="800"
data-size="35"
data-brand="Andrew">
<img src="http://placehold.it/140x80">
<p>Andrew 35<br>$800</p>
</div>
</div>
<form id="filter">
<div>
<input type="checkbox"
name="brand"
value="Andrew" checked>
Andrew
</input>
<input type="checkbox"
name="brand"
value="Sunbaby">
Sunbaby
</input>
<input type="checkbox"
name="brand"
value="Nike">
Nike
</input>
</div>
<div>
<input type="checkbox"
name="category"
value="shoes" checked>
Shoes
</input>
<input type="checkbox"
name="category"
value="shirts">
Shirts
</input>
</div>
<div>
<input type="radio"
name="price"
value="0-9000"
checked>
All
</input>
<input type="radio"
name="price"
value="0-999">
$0-$1000
</input>
<input type="radio"
name="price"
value="1000-2000">
$1000-$2000
</input>
<div>
<div>
<input type="radio"
name="size"
value="0-80"
checked>
All
</input>
<input type="radio"
name="size"
value="0-25">
Small
</input>
<input type="radio"
name="size"
value="26-45">
Medium
</input>
<input type="radio"
name="size"
value="46-80">
Big
</input>
<div>
</form>
</body>
</html>
css
.hidden {display: none;}
.content {border-radius: 5px; border: 1px solid #bbb;padding: 5px; margin: 5px; float: left;}
#filter {clear: left;}
script
var filterContentForm = function(content, form){
var filter = function() {
var checkBoxGroups = {},
radioGroups = {};
var addRadioGroup = function(name){
radioGroups[name] = {
el: $('input[name='+name+']:checked')
};
var n = radioGroups[name];
n.el
.each(function(){
n.range = $(this).val().split('-');
n.from = Number(n.range[0]);
n.to = Number(n.range[1]);
});
};
$('#filter input[type=radio]')
.each(function(){
addRadioGroup($(this).attr('name'));
});
var addCheckBoxGroup = function(name){
checkBoxGroups[name] = {
el: $('input[name='+name+']:checked'),
ch: []
};
var n = checkBoxGroups[name];
n.el.each(function(){
n.ch.push($(this).val());
});
};
$('#filter input[type=checkbox]')
.each(function(){
addCheckBoxGroup($(this).attr('name'));
});
var contents = $(content), all = 0;
contents.removeClass('hidden')
.each(function(){
var $this = $(this),
price = $this.data('price');
for(var c in radioGroups){
var n = radioGroups[c],
d = Number($this.data(c));
if(d < n.from || d > n.to){
$this.addClass('hidden');
all++;
return;
}
}
var show = 0, i;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
var l = Object.keys(checkBoxGroups).length;
if(show < l) {
$this.addClass('hidden');
all++;
}
});
if(all > contents.length - 1)
contents.removeClass('hidden');
};
$(form+' input').change(filter);
filter();
};
filterContentForm('.content', '#filter');
#filter {clear: left;}
The above code is working fine.I just need one small change in this. That is, on start two checkboxes are checked i.e.for brand i.e.Nike and category i.e. shoes. I just want that on the start, these two checkboxes also need to be unchecked,all records visible,but when I am removing the 'checked' from Andrew and Shoes checkbox,Filtering doesnot happen.
Just guide me how to keep all checkboxes unchecked on start and then filtering should work after selecting the checkboxes.
Thanks for help

Your filter code seems to be a little buggy.
Make sure you are adding the jquery js in the header!
To toggle checked/unchecked state of your checkboxes and/or radio-buttons simply add/remove the checked attribute from the tag
<input type="checkbox"
name="category"
value="shoes" **checked**>

Ok so this is the problem:
You are checking the following condition
if(show < l)
where show is the count of filterCategories [ in your case: brand and category] that are checked. This is being compared against l which is count of total filterCategories present.
So, when only one of the categories is checked, this conditions becomes true, and following code
`$this.addClass('hidden');
all++;`
gets executed. This makes your all++ reach the value of contents.length hence your following code gets executed
if(all > contents.length - 1)
contents.removeClass('hidden');
which overrides the filters and shows all the items [ in your case the divs ]
To fix this see the following code. The activeFilterCount variable is the change that is required. Just replace your code from var show=0,i; to all++;} with the following code:
var show = 0, i, activeFilterCount=0;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
if(n.ch.length > 0){
activeFilterCount++;
}
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
if(show < activeFilterCount) {
$this.addClass('hidden');
all++;
}
I know it got a little too lengthy, but I hope it helps you! Let me know if anything is not clear.

Related

How can I get a variable image URL?

So I got a project here with a couple of radiobuttons. The plan is to be able to select a base, a lining, color and a shading technique. The blue box to the right serves the purpose of giving the customer a live overview of example outcome of the selected parts. I want to place an image there, with a variable URL.
My plan would be to do something like: "https://www.example.com/images/calculator/base+line+color+shading.png"
Where base is gotten from the base radio input, and could be for example "fullbody"Where line is gotten from the line radio input, and could be for example "clean"Where color is gotten from the color radio input, and could be for example "colored"Where shading is gotten from the shading radio input, and could be for example "ccel"This would leave us with a variable url of "https://www.example.com/images/calculator/fullbody+clean+colored+ccel.png"
At the same time, I don't want them to have to select all of the inputs to get an overview, if they only select "fullbody", the variable URL should become "https://www.example.com/images/calculator/fullbody.png"
The artist I'm doing this for is rapidly increasing the product base and style choices, and I will be updating it over time, so a solution that is expandable with more options over time would be amazing.
As always, thank you for taking your time to read over, any answers or tips/tricks/hints or pointing in directions is greatly appreciated! Enjoy the weekend folks! <3
small overview of my project layout
data-position="1" is for base group
data-position="2" is for line group
data-position="3" is for color group
data-position="4" is for shade group
..
..
data-position="k" will be for kth value group and so on...
See working example here https://jsfiddle.net/y2khfjwp/40/
<div style="width: 50%; float: Left;">
<h2>
Base
</h2>
<input type="radio" name="base" class="main-inputs" data-position="1" value="fullbody" onchange="makeImage(this)"/>Full Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="halfbody" onchange="makeImage(this)"/>Half Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="xyzbody" onchange="makeImage(this)"/>xyz Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="abcbody" onchange="makeImage(this)"/>abc body<br>
<hr>
<h2>
Line
</h2>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean" onchange="makeImage(this)"/>Clean<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean2" onchange="makeImage(this)"/>Clean2<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean3" onchange="makeImage(this)"/>Clean3<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean4" onchange="makeImage(this)"/>Clean4<br>
<hr>
<h2>
Color
</h2>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored" onchange="makeImage(this)"/>Colored<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored2" onchange="makeImage(this)"/>Colored2<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored3" onchange="makeImage(this)"/>Colored3<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored4" onchange="makeImage(this)"/>Colored4<br>
<hr>
<h2>
Shade
</h2>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel" onchange="makeImage(this)"/>Ccel<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel2" onchange="makeImage(this)"/>Ccel2<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel3" onchange="makeImage(this)"/>Ccel3<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel4" onchange="makeImage(this)"/>Ccel4<br>
</div>
<div style="width: 50%; float: Right;">
OutPut: <img id="final-output-src" src="Please select Options" /><br><span id="final-output">Please select Options</span>
</div>
<script>
var path = [];
function makeImage(element)
{
var imagePath = "";
path[element.getAttribute('data-position')] = element.value;
imagePath = finalImagePath();
document.getElementById("final-output-src").src = imagePath;
document.getElementById("final-output").innerHTML = imagePath;
};
function finalImagePath() {
var imageSrc = "https://www.example.com/images/calculator/";
var selections = "";
for(var i=1 ; i<=path.length ; i++) {
if(typeof path[i] != 'undefined' && path[i] != '') {
if(selections == "") {
selections = selections + path[i];
} else {
selections = selections + "+" + path[i];
}
}
}
if(selections != "") {
selections = selections + ".png";
imageSrc = imageSrc + selections;
}
return imageSrc;
}
</script>
Okay here is a solution to generate the image url:
const partials = document.querySelectorAll('#partials input');
const fullBody = document.getElementById('fullbody');
const baseUrl = 'some-root-url.com/';
const fileType = '.png';
let imageUrl = baseUrl + 'some-default-url' + fileType;
// Add Event Listeners
fullBody.addEventListener('change', function(){
let checked = document.querySelectorAll('#partials input:checked');
// deselect each partial
for(let i = 0; i < checked.length; i++){
checked[i].checked = false;
}
// Set the imageUrl var to the fullbody
imageUrl = baseUrl + this.value + fileType;
// see the imageUrl!
console.log(imageUrl);
});
for(let i = 0; i < partials.length; i++){
partials[i].addEventListener('change', function(){
// uncheck fullBody if checked
fullBody.checked = false;
// init the imageUrl
imageUrl = baseUrl;
// loop through each checked option and add the value to the imageUrl
let checked = document.querySelectorAll('#partials input:checked');
for(let i = 0; i < checked.length; i++){
imageUrl += checked[i].value;
}
// add the file type
imageUrl += fileType;
// see the imageUrl!
console.log(imageUrl)
});
}
And here's the corresponding HTML
<div id="partials">
<label for="base">Base</label><input name="base" type="checkbox" value="base" /><br />
<label for="line">Line</label><input name="line" type="checkbox" value="line" /><br />
<label for="color">Color</label><input name="color" type="checkbox" value="color" /><br />
<label for="Shading">Shading</label><input name="shading" type="checkbox" value="shading" />
</div>
<label for="fullbody">Full Body</label><input name="fullbody" id="fullbody" type="checkbox" value="fullbody" />
And a JSFiddle to demo
One tip for you as well, you want to use checkboxes not radio, as radio are designed for single choices not multiselect.
Hope that helps!

Checkbox arrays

Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>

HTML DIV display none to element adjust size

How can i automatically adjust the size of the div to its VISIBLE content?
I have a page which shows radio buttons but the user can select to view only a specific amount of radiobuttons.
When i click my checkbox to hide the elements They disappear. However the div stays the same size.
How can i fix this?
CODE
<script>
function getElementsByClass( searchClass, domNode, tagName) {
if (domNode == null) domNode = document;
if (tagName == null) tagName = '*';
var el = new Array();
var tags = domNode.getElementsByTagName(tagName);
var tcl = " "+searchClass+" ";
for(i=0,j=0; i<tags.length; i++) {
var test = " " + tags[i].className + " ";
if (test.indexOf(tcl) != -1)
el[j++] = tags[i];
}
return el;
}
function checkChange(checkbox)
{
if (checkbox.checked)
{
if(checkbox.value == "Intel"){
var tabs = getElementsByClass('Intel');
for( i=0; i < tabs.length; i++)
tabs[i].style.display='none';
}
}else if(!checkbox.checked)
{
if(checkbox.value == "Intel"){
var tabz = getElementsByClass('Intel');
for (i =0; i < tabz.length; i ++)
tabz[i].style.display="inline";}
}
}
</script>
<form action="">
<input type="checkbox" name="category" value="Intel" onclick="checkChange(this)" /> Intel processoren<br>
<input type="checkbox" name="category" value="Amd" onclick="checkChange(this)" /> AMD processoren<br>
</form>
</div>
<div id="items">
<form action="get.jsp?value=Processoren" method="post">
// JSP CODE FOR ALL CHECKBOXES !!!//
<hr>
<input type="submit" value="Send">
</div>
</div>
To make div automatically adjusting to its visible content you should set its styles to 'display: block' and 'overflow: visible'.
See the following sample:
$(document).ready(function(){
$("#case1cnt").hide();
$("#case2cnt").hide();
$("#case3cnt").hide();
$("#case1").click(function(){
$("#case1cnt").toggle();
});
$("#case2").click(function(){
$("#case2cnt").toggle();
});
$("#case3").click(function(){
$("#case3cnt").toggle();
});
})
#content {
display: block;
overflow: visible;
margin-top: 16px;
padding: 8px;
background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="case1" type=checkbox /> Case 1<br />
<input id="case2" type=checkbox /> Case 2<br />
<input id="case3" type=checkbox /> Case 3<br />
<div id=content>
<p>Static content</p>
<p id="case1cnt">Case 1 content</p>
<p id="case2cnt">Case 2 content</p>
<p id="case3cnt">Case 3 content</p>
<div>

Change the background of the radio button depending by the answer

I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.

Hide and show product list on basis of multiple categories in javascript

<div class="content" data-category="shoes" data-price="1000" data-brand="Andrew">shoe1</div><br />
<div class="content" data-category="shirts" data-price="1200" data-brand="Sunbaby">shirt1</div><br />
<div class="content" data-category="shoes" data-price="2000" data-brand="Andrew">shoe2</div><br />
<div class="content" data-category="shoes" data-price="800" data-brand="Andrew">shoe3</div><br />
<div class="content" data-category="shirts" data-price="1300" data-brand="Sunbaby">shirt2</div><br />
<div class="content" data-category="shirts" data-price="800" data-brand="Sunbaby">shirt3</div><br />
<input type="checkbox" class="category" category="shoes" id="shoes">shoes
<input type="checkbox" class="category" category="shirts" id="shirts">shirts
<input type="radio" name="range" value="0-9000" checked>All
<input type="radio" name="range" value="0-999">0-1000
<input type="radio" name="range" value="1000-2000">1000-2000
Basically if you select a category from checkbox lets say shoes, then divs only with shoes should get displayed. Then if you filter the results with price, some starting and ending limit, it should show shoes category divs falling in that specific range, Not out of that range.
And in between if you select brand checkbox also.then it should match for all the three checkboxes that is from category and brand and price range
For example:- we selected shoes checkbox, it should show shoe divs; then if we select range as 1000-2000, then it should show shoe1 and shoe2 and not shoe3.
if u select shoe category and then if you select brand checkbox as well.it should filter out on both checkbox basis,and then it should look for price range and match the results,filter the divs.
Please help on this.
<script type="text/javascript">
$("input.category").prop("checked", true).change(function (e) {
$("input[name=range]:checked").trigger("change");
});
$("input.brand").prop("checked", true).change(function (e1) {
$("input[name=range]:checked").trigger("change");
});
$("input[name=range]").change(function (e) {
var toggle = this.checked;
var range = this.value.split('-');
var rangeFrom = parseInt(range[0]);
var rangeTo = parseInt(range[1]);
$(".content[data-price]").each(function(){
var $this = $(this);
var categoryActive = $("#" + $this.data("category")).prop("checked");
var brandActive = $("#" + $this.data("brand")).prop("checked");
var price = parseFloat($this.data('price'));
$this.toggle(price >= rangeFrom && price <= rangeTo && categoryActive);
$this.toggle(price >= rangeFrom && price <= rangeTo && $("#" + $this.data("brand")).prop("checked"));
});
});
</script>
i tried this script with my one buddy's help.
Thanks and Google if You can help on this
you can do something like this :
$("#shoes").click(function (e) {
$('.content[data-category=shoes]').toggle();
});
Solution
HTML
<form id="filter">
<div>
<input type="checkbox"
name="brand"
value="Andrew"
checked>Andrew
</input>
<input type="checkbox"
name="brand"
value="Sunbaby"
checked>Sunbaby
</input>
<input type="checkbox"
name="brand"
value="Nike"
checked>Nike
</input>
</div>
<div>
<input type="checkbox"
name="category"
value="shoes"
checked>Shoes
</input>
<input type="checkbox"
name="category"
value="shirts"
checked>
Shirts
</input>
</div>
<div>
<input type="radio"
name="price"
value="0-9000"
checked>All
</input>
<input type="radio"
name="price"
value="0-999">0-1000
</input>
<input type="radio"
name="price"
value="1000-2000">1000-2000
</input>
<div>
</form>
CSS
.hidden {display: none;}
JS/JQUERY
var filterContentForm = function(content, form){
var filter = function() {
var checkBoxGroups = {},
radioGroups = {};
var addRadioGroup = function(name){
radioGroups[name] = {
el: $('input[name='+name+']:checked')
};
var n = radioGroups[name];
n.el
.each(function(){
n.range = $(this).val().split('-');
n.from = Number(n.range[0]);
n.to = Number(n.range[1]);
});
};
$('#filter input[type=radio]')
.each(function(){
addRadioGroup($(this).attr('name'));
});
var addCheckBoxGroup = function(name){
checkBoxGroups[name] = {
el: $('input[name='+name+']:checked'),
ch: []
};
var n = checkBoxGroups[name];
n.el.each(function(){
n.ch.push($(this).val());
});
};
$('#filter input[type=checkbox]')
.each(function(){
addCheckBoxGroup($(this).attr('name'));
});
var contents = $(content), all = 0;
contents.removeClass('hidden')
.each(function(){
var $this = $(this),
price = $this.data('price');
for(var c in radioGroups){
var n = radioGroups[c],
d = Number($this.data(c));
if(d < n.from || d > n.to){
$this.addClass('hidden');
all++;
return;
}
}
var show = 0, i;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
var l = Object.keys(checkBoxGroups).length;
if(show < l) {
$this.addClass('hidden');
all++;
}
});
if(all > contents.length - 1)
contents.removeClass('hidden');
};
$(form+' input').change(filter);
filter();
};
filterContentForm('.content', '#filter');

Categories

Resources