I am trying to only display the divs that are selected in the checkboxes. This is working fine. I want to make it so that every time the user enters a character in the search box, the list of items is check, so if the user enters "div 4" and all divs are checked, then upon entering the "4", all will disappear except for the substring containing 4.
I want to do this with no submit button, dynamically.
How can I do this?
My code so far is like this :
<html>
<head>
<script type="text/javascript">
<!--
function dynamicSearch() {
document.getElementById('search').value
}
function showMe (it, box) {
var vis = (box.checked) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
//-->
</script>
</head>
<body>
<form>
<label for="search">Search:</label>
<input type="text" name="search" id="search" onkeyup="dynamicSearch()"/>
<input type="checkbox" name="modtype" value="value1" onclick="showMe('div1', this)" />value1
<input type="checkbox" name="modtype" value="value2" onclick="showMe('div2', this)" />value2
<input type="checkbox" name="modtype" value="value3" onclick="showMe('div3', this)" />value3
<input type="checkbox" name="modtype" value="value4" onclick="showMe('div4', this)" />value4
<input type="checkbox" name="modtype" value="value5" onclick="showMe('div5', this)" />value5
<div class="row" id="div1" style="display:none">Show Div 1</div>
<div class="row" id="div2" style="display:none">Show Div 2</div>
<div class="row" id="div3" style="display:none">Show Div 3</div>
<div class="row" id="div4" style="display:none">Show Div 4</div>
<div class="row" id="div5" style="display:none">Show Div 5</div>
</form>
</body>
</html>
Here's something I just hacked together. It needs fleshing out but I think it shows the basic idea.
function dynamicSearch() {
var val = document.getElementById('search').value;
if (val == '')
val = '-1';
var srch = new RegExp(val, "gi");
var els = document.getElementsByClassName('row');
for (var idx in els) {
if (idx != parseInt(idx))
continue;
var el = els[idx];
if (typeof(el.innerHTML) !== 'undefined') {
console.log(el.innerHTML);
if (srch.test(el.innerHTML)) {
el.style.display = 'block';
} else {
el.style.display = 'none';
}
}
}
}
you can make a function, which would watch for document.getElementById('search').value and bind this function to onkeyup event if the search input element.
Related
I am trying to show a Div that contains a button element, but only when BOTH checkboxes have been "agreed" to.
I have tried to use JS to check this and then set the style display when each checkbox is clicked.
HTML:
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
JS:
function showMe(box) {
var chbox1 = document.getElementByID("box1");
var chbox2 = document.getElementByID("box2");
var vis = "none";
if (chbox1.checked && chbox2.checked) {
vis = "block";
break;
}
document.getElementById(box).style.display = vis;
}
Fiddle: https://jsfiddle.net/nhykqodp/2/
I'm kinda new to JS and my HTML knowledge is about 10 years out of date at this point. Any help would be appreciated.
Thanks.
If I run your code, it shows:
Uncaught SyntaxError: Illegal break statement
Thats because a break
can only be used inside a loop.
Furthermore, you have a typo, it should be getElementById instead of getElementByID
Note: The d shouldn't be capitalised
Remove the break
Fix the typos:
function showMe(box) {
var chbox1 = document.getElementById("box1");
var chbox2 = document.getElementById("box2");
var vis = "none";
if (chbox1.checked && chbox2.checked) {
vis = "block";
}
document.getElementById(box).style.display = vis;
}
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
Using an in-line if statement, we can remove the vis variable so we can alter the style right away like so:
function showMe(box) {
const chbox1 = document.getElementById("box1");
const chbox2 = document.getElementById("box2");
document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}
function showMe(box) {
const chbox1 = document.getElementById("box1");
const chbox2 = document.getElementById("box2");
document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
The syntax errors have already been pointed out; for hiding/showing elements these already have an API which is called el.hidden. I recommend you use it.
Aside from that, you shouldn't use inline event handlers like onclick. Instead, use EventTarget.addEventListener().
I've also generalized your code, so that any number of checkboxes can act as toggle for any element, given that element has the id that you define in data-toggle on the checkboxes.
const checkboxes = Array.from(document.querySelectorAll('[data-toggle]'));
function allChecked(toggle) {
return checkboxes.filter(cb => cb.dataset.toggle === toggle).every(cb => cb.checked);
}
for (const checkbox of checkboxes) {
checkbox.addEventListener('change', function() {
document.getElementById(this.dataset.toggle).hidden = !allChecked(this.dataset.toggle);
});
}
<div class="agreement_box">
<input type="checkbox" data-toggle="submit_btn">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" data-toggle="submit_btn">
</div>
<div id="submit_btn" class="profileSubmit_btn" hidden>
<button>
BUTTON
</button>
</div>
Little syntax error just replace document.getElementByID to document.getElementById
I am struggling with this thing for the last few days and trying to obtain specific div details. It was resolved actually and here is the working one - Obtain Related Div Text with jQuery. So if you have seen it, I was using individual buttons for each div section as follows:
<div class="divs">
<div class="heading">
<div class="h2Val"> //Trying to retrieve this value - The id
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>
//Another one is this - CheckBox value
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
<div>
<input type="button" class="btn" value="Get Value" /> //This is the button that was assigned with every div
</div>
</div>
</div>
But now, I am trying to separate the buttons and used anchor tag that's out of the parent div class divs to retrieve those values . But the issue is, it doesn't get the id and values of individual divs. Here is the code snippet:
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $(this).closest('.heading')
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())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<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>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
So I tweaked a bit with the following but it retrieves all the selected div values at a time rather than individual:
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $('.divs').children().closest('.heading')
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())
});
});
Any better way or solution to resolve it?
Update 1: Expected output - When checked on first option and clicked Next, it should show result as follows:
ID: 1 has 1 checked
Values: London
Then when second question comes and the same should happen:
ID: 2 has 1 checked
Values: Charles Babbage
You can get length of .divs and then declare some variable which will have value 0 .So, whenever next button is clicked you can check if the variable value if less then the length of .divs and depending on this either increment value by 1 or start counter again from 0.
Demo Code :
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
//declare
var indexes = 0;
$(".button").click(function() {
//get div length
var lengths = divs.length;
//pass indexes value to get required div
var $container = $('.divs').children().eq(indexes);
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())
//checking if indexes value is less then length of div
if (indexes < (lengths-1)) {
//increment
indexes++;
} else {
//start from 0
indexes = 0;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divs" datas="abc">
<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>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
I have 3 input checkboxes. Each of them displays a div if checked. Because the three has the same JS I have decided to have just one JS including 3 variables (one per input) but it is not working. Before I had three independent JS and it worked fine.
CODE
document.getElementById()
var cb1 = document.getElementById('checkbox1'); checkbox1.onchange = {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
};
var cb2 = document.getElementById('checkbox2'); checkbox2.onchange = {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
};
var cb3 = document.getElementById('checkbox3'); checkbox3.onchange = {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3"> Course 3
</label>
</form>
<br>
<div id ="course1">
Text course 1
</div>
<br>
<div id ="course2">
Text course 2
</div>
<br>
<div id ="course3">
Text course 3
</div>
Fiddle: https://codepen.io/antonioagar1/pen/YOwBeE?editors=1010
After fixing your syntax errors (identation is very imporant, if it was correct in your code you would had see that you have many if statements not closing correclty)
Well, besides those errors, I managed a way to you that you only need a single function to achieve your desired result.
If you see in the HTML part, you'll note that I added some new attributes to checkboxes and divs, called data-idCheck, where the checkbox with data-idCheck will display the div whose have that same attribute.
Check below to see if my code helps you.
var cb1 = document.getElementById('checkbox1');
cb1.onchange = checkChecked;
var cb2 = document.getElementById('checkbox2');
cb2.onchange = checkChecked;
var cb3 = document.getElementById('checkbox3');
cb3.onchange = checkChecked;
function checkChecked(){
let idCheck = this.getAttribute("data-idCheck");
let relatedDiv = document.querySelector("div[data-idCheck='" + idCheck + "']");
if (this.checked) {
relatedDiv.style.display = 'block';
} else {
relatedDiv.style.display = 'none';
}
}
.hiddenDiv{
display: none;
}
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" data-idCheck="1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" data-idCheck="2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" data-idCheck="3"> Course 3
</label>
</form>
<br>
<div id ="course1" class="hiddenDiv" data-idCheck="1">
Text course 1
</div>
<br>
<div id ="course2" class="hiddenDiv" data-idCheck="2">
Text course 2
</div>
<br>
<div id ="course3" class="hiddenDiv" data-idCheck="3">
Text course 3
</div>
I'm trying to write some JavaScript that could be used throughout my app, and allow a checkbox to show/hide a nearby element.
If I have these elements:
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control"
data-val="true" id="IsActive"
name="IsActive"
onclick="CheckboxOptionsToggle(this);"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
And this script:
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox).closest(optionElement).show();
} else {
$(thisCheckbox).closest(optionElement).hide();
}
}
But this isn't working. I would like the checkbox with the onclick="CheckboxOptionsToggle(this);" to trigger the options element in the same optionable div to either show or hide.
What am I doing wrong in my JavaScript/jQuery?
UPDATE: This is my final solution:
$('.optionToggle').on('change', function () {
$(this).closest('.optionable').find('.options').toggle(this.checked);
});
$(document).ready(function () {
var toggleElements = document.body.getElementsByClassName('optionToggle');
for (var i = 0; i < toggleElements.length; i++) {
var thisCheck = $(toggleElements[i]);
thisCheck.closest('.optionable').find('.options').toggle(thisCheck.prop('checked'));
}
});
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control optionToggle"
data-val="true" id="IsActive"
name="IsActive"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
Be more generic, and stop using inline event handlers
$('[type="checkbox"]').on('change', function() { // or use class to not attach to all
$(this).closest('.optionable').find('.options').toggle(this.checked);
}).trigger('change');
FIDDLE
You can change it like
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox)..closest('div.optionable').find(optionElement).show();
} else {
$(thisCheckbox)..closest('div.optionable').find(optionElement).hide();
}
}
I would stay away from .closes, because it is so specific, instead I would go with more reusable code like so:
HTML:
<input type="checkbox" id="toggler" data-target-class="some-div" class="toggler" value="myValue" checked> Toggle Me
<div class="some-div">
Some Text within the div.
</div>
JS:
$('#toggler').on('click', function() {
var targetClass = $(this).data('target-class');
$('.' + targetClass).toggle($(this).checked);
});
JSFiddler: https://jsfiddle.net/ro17nvbL/
I am using data element on the checkbox to specifiy which divs to show or hide. This allows me to not only hide/show divs but anything n the page, and not only one instance but as many as needed. Way more flexible - still does the same job.
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.