jQuery show only divs matching multiple checkbox parameters - javascript

I am trying to create a system to filter through some tags by hiding and showing the appropriate items.
When .brandFilter is clicked, it needs to show the div using the id of the checkbox. When .prodFilter is clicked, it needs to show the corresponding colors but not show any deselected ID's (unless none have been selected, in which case show everything matching the color).
Right now when I click Epson and HP it works; but when I click Red it will show the red Lexmark product which is not desired; it was already filtered out when I selected the brand. Ideally clicking #brnd_HP, #brnd_Epson and #typ_Red will display Product A and F.
Deselecting a filter should "undo" whatever previous work it did.
Below is the markup I have now:
<h2>Brand</h2>
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Canon" />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Epson" />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_HP" />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Lexmark" />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Xerox" />
<h2>Color</h2>
<input type="checkbox" class="prodFilter" name="typeFilter" id="typ_Red" />
<input type="checkbox" class="prodFilter" name="typeFilter" id="typ_Blue" />
<div class="prdbx brnd_Epson typ_Red">Product A</div>
<div class="prdbx brnd_Canon typ_Red">Product B</div>
<div class="prdbx brnd_Epson typ_Blue">Product C</div>
<div class="prdbx brnd_Lexmark typ_Red">Product D</div>
<div class="prdbx brnd_Canon typ_Blue">Product E</div>
<div class="prdbx brnd_HP typ_Red">Product F</div>
The jQuery is not functioning as intended, but this is what I have so far. I really can't seem to wrap my head around the seemingly query like nature of toggling visibility with multiple parameters like this. The HP/Epson part works fine, but once the color is introduced it simply shows everything relating to the color ID.
<script>
jQuery(document).ready(function(){
$('.brandFilter').click(function(e) {
$('.brandbx').hide();
var thisFilter = "";
$('input[name=brandFilter]:checked').each(function(e) {
thisFilter += '.'+this.id;
});
$(thisFilter).show();
});
// when a filter is clicked
$('.prodFilter').click(function(e) {
$('.prdbx').hide(); // hide all products
var thisFilter = "";
var thisCounter = 0;
// for each clicked filter
$('.prodFilter:checked').each(function(e) {
thisFilter += '.'+this.id;
$('.'+this.id).show(); // show the products matching filter
thisCounter++;
});
if(thisCounter == 0){
$('.prdbx').show(); // if no clicked filters, show all products
$('.brandbx').show();
}
});
});
</script>

You need to combine the filters which means persisting the filter from the first checkbox somehow. This works.
var thisFilter1 = "";
jQuery(document).ready(function(){
$('.brandFilter').click(function(e) {
$('.brandbx').hide();
thisFilter1 = "";
var sep = ""
$('input[name=brandFilter]:checked').each(function(e) {
thisFilter1 = thisFilter1 + sep + '.'+this.id;
sep = ","
});
$(thisFilter1).show();
});
// when a filter is clicked
$('.prodFilter').click(function(e) {
$('.prdbx').hide(); // hide all products
var thisCounter = 0;
var thisFilter = "";
var sep=""
// for each clicked filter
$('.prodFilter:checked').each(function(e) {
thisFilter = thisFilter + sep + '.' + this.id;
sep=","
thisCounter++;
});
if(thisCounter == 0){
$('.prdbx').show(); // if no clicked filters, show all products
$('.brandbx').show();
}
else {
$('.prdbx').each(function() {
if ($(this).is(thisFilter1) && $(this).is(thisFilter)){
$(this).show()
}
})
}
});
});
EDIT: Updated for multiple selection combos. Say hello to jquery .is(). An interesting function that does not return a jq object so can't be chained but can be used inside an if test. You can now have Canon red, blue or red + blue, or HP + Canon blue, etc.

I might have not understand the desired functionality because in my code none of the products is shown at the beginning.
HTML:
<h2>Brand</h2>
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Canon" /> Canon
<br />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Epson" /> Epson
<br />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_HP" /> HP
<br />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Lexmark" /> Lexmark
<br />
<input type="checkbox" class="brandFilter" name="brandFilter" id="brnd_Xerox" /> Xerox
<br />
<h2>Color</h2>
<input type="checkbox" class="prodFilter" name="typeFilter" id="typ_Red" /> Red
<br />
<input type="checkbox" class="prodFilter" name="typeFilter" id="typ_Blue" /> Blue
<div class="prdbx brnd_Epson typ_Red show">Epson Red</div>
<div class="prdbx brnd_Canon typ_Red show">Canon Red</div>
<div class="prdbx brnd_Epson typ_Blue show">Epson Blue</div>
<div class="prdbx brnd_Lexmark typ_Red show">Lexmark Red</div>
<div class="prdbx brnd_Canon typ_Blue show">Canon Blue</div>
<div class="prdbx brnd_HP typ_Red show">HP Red</div>
CSS:
.prdbx {
display: none;
}
.prdbx.show {
display: block;
}
JavaScript:
jQuery(document).ready(function() {
$(".brandFilter").on('change', function() {
//Filter by brand first
filterByBrand();
//Then filter by color
filterByProd();
});
$(".prodFilter").on('change', function() {
filterByProd();
});
});
function filterByBrand() {
var $allBrands = $(".brandFilter");
if (!$allBrands.filter(':checked').length) {
//If all brand checkboxes are unchecked, show all prdbx divs
$('.prdbx').addClass('show');
} else {
for (var i = 0; i < $allBrands.length; ++i) {
var $brand = $allBrands.eq(i);
//If a brand is checked show it, otherwise hide it
if ($brand.is(':checked')) {
$('.' + $brand.attr('id')).addClass('show');
} else {
$('.' + $brand.attr('id')).removeClass('show');
}
}
}
}
function filterByProd() {
var $allProdFilters = $(".prodFilter");
var noneIsSelected = true;
for (var i = 0; i < $allProdFilters.length; ++i) {
var $prodFilter = $allProdFilters.eq(i);
var $prod = $('.' + $prodFilter.attr('id'));
//If the checkbox is checked
if ($prodFilter.is(':checked')) {
noneIsSelected = false;
if (!$prod.hasClass('show')) {
$prod.addClass('show');
}
} else {
$prod.removeClass('show');
}
}
//If no color is selected, filter by brand
if (noneIsSelected) {
filterByBrand();
}
}
And here is the fiddle: https://jsfiddle.net/mehmetb/m2zLt6Lo/

Related

Get Specific Div Content Based On Id

I am trying to get specific div content based on id. As an example, I've the following contents one by one in the front-end using div:
Question 1
User clicks next, then the second question within the div and so on will come up. When there will be no questions left and user clicks next again, it'll show the question numbers as follows: Say for three questions at the end, a similar list will appear in the front-end
Question 1 Question 2 Question 3
When user will click in any of the question, it should take the user to that specific question. Notice that, this isn't an anchor and it has to be done using the div section. Here's a fiddle that I was trying to work with - JS Fiddle
In the code, I've a div area that remains hidden initially, specifically the question numbers that'll appear at the end. So it reaches the last question, it enables that div area and shows the question number. Here is the code snippet:
$(".getVal").click(function () {
var $container = $('.divs').children().eq();
var id = $(".h2Val").text().trim();
var id2 = $(this).attr("data-id"); //Assigned data-id to match the question id
if (id.match(id2)) { //When match found, trying to enable the div with question
$(".hideSection1").show();
$(".hideSection2").hide();
}
});
Now the problem I face, is it actually possible to get that specific div with question as this isn't an anchor or href or any better way to overcome this issue? In my case, it shows the question but the last one but required to obtain corresponding questions clicking on question numerbers.
Code Snippet:
$(document).ready(function() {
$(".hideSection2").hide();
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
//declare
var indexes = 0;
$(".button").click(function() {
//get div length
var lengths = divs.length;
//checking if btn clicked is next
if ($(this).is('#next')) {
//checking if value if less then length
if ((indexes < (lengths - 1))) {
//increment
//remove
$(this).prop('disabled', false);
$(this).css("background-color", "blue");
console.log("in - " + indexes)
//show div
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
//to show result
show_data1(indexes);
indexes++;
} else {
$(".hideSection2").show();
$(".hideSection1").hide();
console.log("i am in last question reached")
$(this).prop('disabled', true); //disable
$(this).css("background-color", "#00FFFF"); //chnagecolor
$("#prev").css("background-color", "blue");
}
} else if ($(this).is('#prev')) {
//chcking id value is not 0
if (indexes != 0) {
//remove
$(this).prop('disabled', false);
$(this).css("background-color", "blue");
indexes--;
//show
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
console.log("back - " + indexes)
show_data1(indexes); //show result
} else {
console.log("no back question")
//disabled
$(this).prop('disabled', true);
//add color chnage
$(this).css("background-color", "#00FFFF");
$("#next").css("background-color", "blue");
}
}
});
function show_data1(indexes1) {
//pass indexes value to get required div
var $container = $('.divs').children().eq(indexes1);
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function() {
return this.value
}).get();
//console.clear()
console.log('ID: ' + id + ' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
}
$(".getVal").click(function() {
var $container = $('.divs').children().eq();
var id = $(".h2Val").text().trim();
var id2 = $(this).attr("data-id");
//alert($(this).attr("data-id"));
if (id.match(id2)) {
//alert(id + $(this).attr("data-id"));
$(".hideSection1").show();
$(".hideSection2").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="hideSection1">
<div class="divs">
<div class="heading">
<div class="h2Val">1</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div><input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">2</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
<div class="heading">
<div class="h2Val">3</div>
<div>Who invented computehttr?</div>
<div class="heading2">
<div><input type="checkbox" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
</div>
<div class="hideSection2">
<div class="container">
<div class="row">
<div class="divs2">
<a class="getVal" data-id="1">1</a>
<a class="getVal" data-id="2">2</a>
<a class="getVal" data-id="3">3</a>
</div>
</div>
</div>
</div>
You don't need to compare if (id.match(id2)) { because your questions are shown in sequence so we can use divs.eq(id).. to show only div which is clicked by user and to show answer we can pass this id value to show_data1(indexes1) to show answer as well when question is clicked.Also , i have subtract one from the id value because div index will start from 0.
Demo Code :
$(document).ready(function() {
$(".hideSection2").hide();
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
//declare
var indexes = 0;
$(".button").click(function() {
//get div length
var lengths = divs.length;
//checking if btn clicked is next
if ($(this).is('#next')) {
//checking if value if less then length
if ((indexes < (lengths - 1))) {
//increment
//remove
$(this).prop('disabled', false);
$(this).css("background-color", "blue");
console.log("in - " + indexes)
//show div
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
//to show result
show_data1(indexes);
indexes++;
} else {
$(".hideSection2").show();
$(".hideSection1").hide();
console.log("i am in last question reached")
$(this).prop('disabled', true); //disable
$(this).css("background-color", "#00FFFF"); //chnagecolor
$("#prev").css("background-color", "blue");
}
} else if ($(this).is('#prev')) {
//chcking id value is not 0
if (indexes != 0) {
//remove
$(this).prop('disabled', false);
$(this).css("background-color", "blue");
indexes--;
//show
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
console.log("back - " + indexes)
show_data1(indexes); //show result
} else {
console.log("no back question")
//disabled
$(this).prop('disabled', true);
//add color chnage
$(this).css("background-color", "#00FFFF");
$("#next").css("background-color", "blue");
}
}
});
function show_data1(indexes1) {
//pass indexes value to get required div
var $container = $('.divs').children().eq(indexes1);
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function() {
return this.value
}).get();
//console.clear()
console.log('ID: ' + id + ' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
}
$(".getVal").click(function() {
//get id
var id = $(this).attr("data-id");
$(".hideSection1").show();
$(".hideSection2").hide();
//subtract one , because div starts from 0 ,1..etc
var new_id= id - 1;
//show div
divs.eq(new_id).show().siblings().hide();
index = new_id; //settting value of index again for click of next button
indexes = new_id; //setting value for index
show_data1(indexes) //show answer as well when user click of question no.
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hideSection1">
<div class="divs">
<div class="heading">
<div class="h2Val">1</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div><input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">2</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
<div class="heading">
<div class="h2Val">3</div>
<div>Who invented computehttr?</div>
<div class="heading2">
<div><input type="checkbox" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
</div>
<div class="hideSection2">
<div class="container">
<div class="row">
<div class="divs2">
<a class="getVal" data-id="1">1</a>
<a class="getVal" data-id="2">2</a>
<a class="getVal" data-id="3">3</a>
</div>
</div>
</div>
</div>

How can I save a total score in localstorage each time a checkbox is checked

I've built a small game using checkboxes with images. When the user comes across the item in the picture they select the checkbox and the message changes on screen. Because this is a tourist guide website and game, the user will leave the page to look at other pages, selecting the pictures as they come across the item. Therefore I needed to save the checked boxes in localstorage so that the data persists. I have some javascript that dsave the checked boxes.
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened.
My javascript for calculating the total and storing the checkboxes is below.
$('.dp-spotter-switch input[type="checkbox"]').click(function () {
if (!$(this).is(':checked')) {
$(this).parent('.dp-spotter-switch').removeClass('spotter-scale');
} else {
$(this).parent('.dp-spotter-switch').addClass('spotter-scale');
}
});
function showDiv() {
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
(function () {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function () {
localStorage.setItem(storageId, this.checked);
});
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dp-spotter-container">
<div class="dp-top-paragraph">
<p>Some text</p>
<p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p>
<div id="getScoreLabel" style="display:none; text-align: center;">
<div class="dp-your-score-text" id="getScore">Your Score</div>
<input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/>
</div>
</div>
<br/>
<br/>
<!-- Spotter 1 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1">
<span class="dp-spotter-slider"></span>
<span class="dp-spotter-text-label">Item 1- 3 Points</span>
</label>
</div>
<!-- Spotter 2 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 2 - 3 Points</p>
</label>
</div>
<!-- Spotter 3 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">ITem 3 - 5 Points</p>
</label>
</div>
<!-- Spotter 4 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 4 - 10 Points</p>
</label>
</div>
Get Your Score
</div>
I'm looking for a way to add to the existing function for the checkboxes if possible.
Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action.
Since you're using jQuery, I've gone ahead and provided a jQuery solution:
Used .attr() to set the checkbox based on local storage
Called totalIt when showing showDiv
If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function
Demo
https://repl.it/#AnonymousSB/SO53500148
Solution
function showDiv() {
totalIt();
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
function setupBox(box) {
var storageId = box.attr("store");
var oldVal = localStorage.getItem(storageId);
box.attr('checked', oldVal === "true" ? true : false)
box.change(function() {
localStorage.setItem(storageId, this.checked);
});
}
$(document).ready(function () {
$( "input[type='checkbox'][store]" ).each(function( index ) {
setupBox($( this ));
});
})
You can open Chrome Dev Tools, go to Application, and see your local storage

create div dynamically by passing css id and class to jquery method

I have div which needs to be repeated(create dynamically) on a button click.i have a working code,but it needs to be used many places across pages so i would like to make it a generic one,like i need to pass only particular div id as an input parameter to that method.
function textbox_add(id){
console.log(id)
var counter = 0;
$('#'+id).on('click','.newField', function () {
console.log(counter);
if(counter >= 3){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
counter++;
});
$('#'+id).on('click','.remove', function () {
if (counter == 0)
{
return false
}
$(this).parent().remove();
counter--;
});
}
if i use it outside the method it works perfect.The goal is to create 4 text boxes dynamically and if i remove it should remove one by one.
here is my fiddle
Demo
Issues facing when i place inside method are:
On first click it creates single div on second click it creates two div's then continues for further click's.
On clicking remove it works like create.
when i click new again it creates the total of removed,created(earlier) all the div's.
I am not able to find where am missing.
I am not too sure what you are trying to do with the id (I assume it is your div id) that you are adding but you can try replacing your counter with a count of the elements:
function textbox_add(id){
$('#'+id).on('click','.newField', function () {
if($("#" + id + " > .addNew").length >= 4){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
});
$('#'+id).on('click','.remove', function () {
if ($("#" + id + " > .addNew").length == 1)
{
return false
}
$(this).parent().remove();
});
}
textbox_add('test');
working Fiddle
OP basically wants an onclick(html) on the add button, like:
function textbox_add(id) {
if ($("#" + id + " > .addNew").length >= 4) {
alert("Reached Maximum");
return false;
}
var newthing = $('#'+id+' .addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','').end();
$('#' + id).append(newthing);
$("#" + id + " > .addNew").on('click', '.remove', function () {
if ($("#" + id + " > .addNew").length === 1) {
return false;
}
$(this).parent().remove();
});
}
working codePen
It works fine, fiddle
You need to pass a wrapper id since you're cloning the .addNew content.
Example:
<div class="container" id="test">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
JS
textbox_add('test');
Your code was actually working well when you use id as selector, but worked wrong (adding multiple times new inputs for example) when you were using class as selector (because multiple elements share the same class).
I have edited it so you can use with id and class selectors:
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div id="other_container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JS
function textbox_add(selector){
console.log(selector);
var max_allowed = 3;
$(selector).on('click','.newField', function () {
console.log($(this).parents(selector).find(".addNew").length);
if($(this).parents(selector).find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
console.log($(this).parents(selector));
$(this).parents(selector).append(newthing);
});
$(selector).on('click','.remove', function () {
if (!$(this).parents(selector).find(".addNew").length > 1){
return false
}
$(this).parent().remove();
});
}
textbox_add(".container");
textbox_add("#other_container");
And here is the working JSFiddle.
I think that this is not the correct way to approach the problem, but the OP really wants to do it this way.
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)"/>
<br />
<br />
</div>
</div>
JS
function textbox_add(element){
var max_allowed = 3;
if($(element).parents(".container").find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing = $('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','textbox_remove(this)').unbind('click').end();
$(element).parents(".container").append(newthing);
}
function textbox_remove(element){
if (!$(element).parents(".container").find(".addNew").length > 1){
return false
}
$(element).parent().remove();
}
Working JSFiddle
I think this might be what you are trying to do. The main thing I'm not sure of is what you intend to pass in as the id parameter. But tell me if this fills the bill.
http://jsfiddle.net/abalter/xdsacvdm/12/
html:
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JavaScript:
$('#createField').on('click', function () {
//alert('new field clicked');
var el = createField('some-id', $('#generator').val());
$('.container').append(el);
});
function createField(id, text) {
var numFields = $('.container').find('.added').length;
if (numFields>3)
{
alert("Maximum reached");
return false;
}
var $outerDiv = $('<div>').addClass('newOne').addClass('added').attr('id', id);
var $textBox = $('<input>').attr({'type': 'text','value': text});
var $button = $('<input>').attr({'type': 'button' , 'value': 'Remove Field!'});
$outerDiv.append($textBox);
$outerDiv.append($button).append('<br/>').append('<br/>');
$button.on('click', function(){
$(this).closest('div').remove();
});
return $outerDiv;
}

find a div by classname and replace it with a div based on onclick - jquery

There are 8 divs and an empty div. Also there are 8 checkboxes. Initially 4 divs are displayed and the remaining are display:none and 4 checkboxes are checked and remaining are uncheked
The Fiddle link is here
This is my code
<div class="container">
<div class="empty" style="display:none;"></div>
<div class="content div_box_1">
<div class="box " style="background:black;"></div>
</div>
<div class="content div_box_2">
<div class="box " style="background:blue;"></div>
</div>
<div class="content div_box_3">
<div class="box " style="background:yellow;"></div>
</div>
<div class="content div_box_4">
<div class="box " style="background:orange;"></div>
</div>
<div class="content div_box_5">
<div class="box " style="background:pink; display:none;"></div>
</div>
<div class="content div_box_6">
<div class="box " style="background:indigo; display:none;"></div>
</div>
<div class="content div_box_7">
<div class="box " style="background:red; display:none;"></div>
</div>
<div class="content div_box_8">
<div class="box " style="background:skyblue; display:none;"></div>
</div>
<div class="checks">
<input type="checkbox" name="box1" checked value="1" class="css-checkbox"/>black
<input type="checkbox" name="box2" checked value="2" class="css-checkbox"/>blue
<input type="checkbox" name="box3" checked value="3" class="css-checkbox"/>yellow
<input type="checkbox" name="box4" checked value="4" class="css-checkbox"/>orange
<input type="checkbox" name="box5" value="5" class="css-checkbox"/>pink
<input type="checkbox" name="box6" value="6" class="css-checkbox"/>indigo
<input type="checkbox" name="box7" value="7" class="css-checkbox"/>red
<input type="checkbox" name="box8" value="8" class="css-checkbox"/>sky-blue
When I uncheck any of these 4 checked boxes the respective div must hide and the class=empty div must be shown eg if I uncheck checkbox with value=2 then div with class="div_box_2 must be hidden and in that place div with class=empty must be displayed and again when checkbox with value=5 or value=6 or value=7 or value=8 is checked then the div with class=empty must be hide and the corresponding div with class=div_box_5 or class=div_box_6 or class=div_box_7 or class=div_box_8 must be displayed in the place of empty div.
Its like removing a div and putting a default div in that place and when again some other div is to be displayed then that div must be displayed in the place of default div
How is this possible?
Please anyone help.
Thank you in advance
What you need is a empty container is each of the content element. You can use a script to add it
//add an empty container to all content elements
$('.container .content').append('<div class="empty" style="display:none;"></div>');
$("input.css-checkbox:checkbox").click(function () {
var cval = $(this).val();
var $div = $(".div_box_" + this.value).slideToggle("fast");
$div.next()[this.checked ? 'slideUp' : 'slideDown']("fast");
})
Demo: Fiddle
EDIT
JSfiddle: click
I changed a few thing:
I removed your style from your HTML and put it in your CSS;
You want to replace the divs so there is no need to hide any;
Let me explain the JS:
var divs = [];
divs.push('<div class="content" id="empty">' +
'<div class="box div_box_0 empty"></div>' +
'</div>');
$('.box').each(function (index) {
divs[index+1] = $(this).parent();
$(this).parent().remove();
});
var selected = [];
var max_boxes = 4;
$('.css-checkbox').each(function () {
if ($(this).is(':checked') && selected.length < max_boxes) {
selected.push(divs[selected.length + 1]);
} else {
$(this).attr('checked', false);
}
});
while (selected.length < 4) {
selected.push(divs[0]);
}
for (var i in selected) {
$('.container').append(selected[i]);
}
$(".css-checkbox").click(function(){
if ($('.css-checkbox:checked').length > 4) {
$(this).attr('checked', false);
} else {
var cval = $(this).val();
var checked = $(this).is(':checked');
if (checked) {
var empty = $.inArray(divs[0], selected);
selected[empty] = divs[cval];
$('#empty').replaceWith(divs[cval]);
} else {
var filled = $.inArray(divs[cval], selected);
selected[filled] = divs[0];
$('.container').find(divs[cval]).replaceWith(divs[0]);
}
}
});
First I create an array with the divs so you can place and replace them. The empty div has to be put in manually, since you want this one more than once. In the array you get a reference to the element. Next i remove each div out of your html.
Next I get the selected boxes and put the div by value in the selected array. After that I append the first 4 selected divs to the container.
The click function checks if there are 4 boxes clicked, when you click on a 5th one it removes the check immediately. Next there is a check to see if you checked or unchecked the checkbox. When you check it, replaces the first empty div with the selected div. If you uncheck it replaces the selected div with an empty div.
Try this Demo
$(function() {
var selectCheckBox = $(".checks input:checkbox")
$(selectCheckBox).click(function() {
var checkingValue = $(this).val()
if(checkingValue == 1){
$('.div_box_1').toggle();
}
else if(checkingValue == 2){
$('.div_box_2').toggle();
}
else if(checkingValue == 3){
$('.div_box_3').toggle();
}
else if(checkingValue == 4){
$('.div_box_4').toggle();
}
})
var selectHiddenChecks = $('.checks input:checkbox')
$(selectHiddenChecks).click(function() {
var checkingValue = $(this).val();
if(checkingValue == 5) {
$('.div_box_5').toggle();
}
else if(checkingValue == 6) {
$('.div_box_6').toggle();
}
else if(checkingValue == 7) {
$('.div_box_7').toggle();
}
else if(checkingValue == 8) {
$('.div_box_8').toggle();
}
})
})

Checkbox not running selected items instead it runs all

jQuery script which opens selected box in new window one by one for specific time. But it runs all boxes on click button whether i check anything or not I am so Confused.
My jQuery code:
function bon()
{
var field = document.getElementsByName('list');
var len = field.length;
var j=0;
for (i = 0; i < field.length; i++)
{
lk[j] = document.getElementById('addlink_'+i).value;
j++;
}
win = window.open("","myWindow","height=500,width=500,menubar=no,status=no");
process();
var interval = document.getElementById('interval').value;
window.setInterval(function(){ process();}, interval);
}
function process()
{
if(oldval<lk.length)
{
var ln =lk[oldval];
win.location.href =ln;
//$.post("updateclick.php",{dbid:recordid},function(data) { document.getElementById(countid).innerHTML = data; });
oldval =oldval+1;
}
else
{
window.location.href=location.href;
}
}
function process1(a,b)
{
if(document.getElementById('chkbox_'+a).checked==true)
{
}
else
{
thisimg(a,b);
}
}
And my HTML code is:
<div class='posts'>
<input style='float:left; height:85px;' type='checkbox' name='list' value='chck_".$counter."' id='chkbox_".$counter."'/>
<div class='title box' onclick='process1(".$counter.",".$row['id'].")'>
<div style='float:left;' onclick='thisimg(".$counter.",".$row['idDiv1'].")'>
<img src='".$imgpath."' height='50' width='50' />
</div>
<div class='click' style='float:right;'>
<b>Clicks <br/>
<div id='count_".$counter."'> ".$click." </div>
<input type='hidden' id='addlink_".$counter."' value='".$app_link."' rel='nofollow'/></b>
</div>
<div style='float:left; width:100px; overflow:hidden; white-space: pre;'>
<b> ".$title."</b>
<br/>".$beforetime."
</div>
</div>
</div>
This is my button code:
<select id="interval">
<option value="5000"> 5 Seconds</option>
<option value="10000"> 10 Seconds</option>
</select>
<input class="butn" type="button" value="Collect" onclick="bon()" />
Working: the user has to select the check boxes which they want to open in new window one by one for specific time( provided in my option box). But whether i check any one or not it executes one by one all like it selects all check boxes.
Ok here is the actual HTML that prints
<div class=posts>
<input style='float:left; height:85px;' type=checkbox name=list value=chck_0 id=chkbox_0 />
<div class='title box' onclick='process1(0,190757)'>
<div style='float:left;' onclick='thisimg(0,190757)'>
<img src='/images/3c59e768eefb1d5d4a0bfdf0ae23cf5a.png' height=50 width=50 />
</div>
<div class=click style='float:right;'><b>Clicks <br/>
<div id=count_0> 0
</div>
<input type=hidden id=addlink_0 value='/link/zqdba3' rel=nofollow></b>
</div>
<div style='float:left; width:100px; overflow:hidden; white-space: pre;'> <b> Title</b><br/>2 Hs 31 Ms ago
</div>
</div>
</div>
Please help I am very confused.
You are iterating over all of your addlink_ inputs without looking at the checkbox. If the ith checkbox is checked, then push the corresponding input element's value onto the array.
var field = document.getElementsByName('list');
var len = field.length;
lk = [];
for (i = 0; i < len; i++) {
if(field[i].checked) {
lk.push(document.getElementById('addlink_'+i).value);
}
}

Categories