I want to make a JavaScript function, which, after pressing a button, takes the list of checkbox elements with their content, checks all the checkboxes, creates a div element with these checkboxes and writes the result to the HTML form.
Here is my code:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
$("formInput").find('.chk').prop("checked", true);
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
}
Here is the HTML Div element with the list of checkbox elements. They also appear dynamically. Initially, Div is empty.
<div id = "selectedList" class = "col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br><br>
</div>
And this is the HTML form, where I want my result to appear:
<form id="formInput">
</form>
The problem here is that it checks all the checkboxes in my list, but in the resulting HTML form they appear unchecked again. What is wrong with it? Thank you
Besides replacing prop() to attr() as Rik Lewis correctly recommended you can alternately put the line
$("formInput").find('.chk').prop("checked", true);
at the bottom of the function and add the # character in front the selector id like this:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id", "selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML + '<br>' + myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectedList" class="col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br>
<br>
<ul>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<ul>
</div>
<form id="formInput">
</form>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
container.append($(html));
}
</script>
Related
trying to create a dynamic button system to add/remove inputs on clicks. I have the addButton working but not the deleteButton. What am I missing?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
The problem is, that $(this) inside the delete button handler refers to the minus button. That minus button is not inside each of the items (It's at the top. and doesn't have a parent div), so you need to reference the element you want to delete another way. In my case below, I'm selecting the last <div> in $(wrapper):
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(wrapper).find('div:last').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Also you can do it with pure JS using child Nodes. :D
Sometimes pure JS is beater than JQ
Explanation:
remove is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use removeChild.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Try below solution, I care about the back end also because you have to send the data to back end developer so you have to give the array name for input fields such as name="person[]". anyway you can try this solution also.
$(document).ready(function(){
var static_html = '<input type="text" name="person[]" class="input_fields" />';
$("#plus").click(function(){
if($(".input_fields").length < 20 )
$("#dynamic_field_container").append(static_html);
});
$("#minus").click(function(){
if($(".input_fields").length > 1 )
$(".input_fields:last").remove();
else
alert("This is default field so u can't delete");
});
});
.input_fields{
display:block;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="fa fa-plus fa-4x" id="plus"> </span>
<span class="fa fa-minus fa-4x" id="minus"> </span>
<div id="dynamic_field_container">
<input type="text" name="person[]" class="input_fields" />
</div>
In the text field inputAddLabel some character is entered. When you click the Add tag button, the eventpushLabel ()is triggered. However, not every symbol should be added, but only one that is contained in listAlphabet. That is, a check must be carried out on the belonging of the added label to the alphabet.
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
if(alph.length == 1){
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
} else { alert('error');}
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>
Keep track of the pushed symbols (alphabet) and use them to filter the label:
var allowedLabels = [];
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
allowedLabels.push(alph);
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
document.getElementById("inputAddAlphabet").value = "";
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
if (allowedLabels.indexOf(label) >= 0) {
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
document.getElementById("inputAddLabel").value = "";
} else { alert('error');}
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>
I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/
<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');