How to show all divs that contain the similar combination of classes - javascript

I would like to show specific posts on a Wordpress page and hide all others. What posts are to be shown, should depend on checkboxes checked on top of the page. A checkbox corresponds with a class. When (for example) two checkboxes are checked (two classes selected in essence), only posts containing at least those two classes in their wrapping div (besides a possible third or fourth class they may have) should be shown (and all the other posts hidden) instantly on the page.
Does anyone of you know how to pull this off?
I already managed to get the tags assigned to a post in the CMS and transfer those tags to the wrapping div of that very post as its class names, so far so good.
How to write the last piece of needed code from scratch I find very difficult to do with the small amount of knowledge I have. I understand that first the desired classes should be gathered (selected through the checked checkboxes). Then a condition should be formed (class1 AND class3 AND class7 have been selected). Then, if that condition is true for a post (‘your wrapping div contains class1, class3 and class7’), only then the post should be shown. The post could also (for example) contain class2, that’s fine, the filter though is made up of the combination of class1, class3 and class7 being present within the wrapper div, as long as that’s true, it may be shown).
I’m sure this should be a stroll through the park for a lot of you, for me it’s still pretty hard to realise from scratch, so any help you guys could give me is highly appreciated! Thanks in advance!
Thanks for your response so far, guys, closest thing I found online so far is this:
$("#filters :checkbox").click(function() {
$("div").hide();
$("#filters :checkbox:checked").each(function() {
$("." + $(this).val()).show();
});
});
It comes from this setup: http://jsfiddle.net/6wYzw/41/ > here it shows a post when its wrapping div contains classX AND/OR classY, see its working example. I reckon the part where it says
$("." + $(this).val()).show();
... needs to be adjusted, so that right here all the checked checkboxes/classes so far are taken into account using AND, not OR. Is this the only line which actually has to be adjusted in order to make my desired setup work the way I want it too?
#Lisrael > all posts should be displayed at first, then the filter starts to kick in as soon as checkboxes are starting to be clicked just like you said indeed.

Found out how to do this! With the help of an example which came close already and lot's of 'sub'examples here and there. See the code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3 align="center">Boardgamefilter</h3>
<form name="gamesettings">
<input type="checkbox" name="gamesetting" value="1p">1p<br />
<input type="checkbox" name="gamesetting" value="2p">2p<br />
<input type="checkbox" name="gamesetting" value="3p">3p<br />
<input type="checkbox" name="gamesetting" value="4p">4p<br />
<input type="checkbox" name="gamesetting" value="5p">5p<br />
<input type="checkbox" name="gamesetting" value="6plus">6plus<br />
<br />
<input type="checkbox" name="gamesetting" value="15m">15m<br />
<input type="checkbox" name="gamesetting" value="30m">30m<br />
<input type="checkbox" name="gamesetting" value="45m">45m<br />
<input type="checkbox" name="gamesetting" value="60m">60m<br />
<input type="checkbox" name="gamesetting" value="90m">90m<br />
<input type="checkbox" name="gamesetting" value="120mplus">120mplus
<br />
<br />
<input type="button" name="Un_CheckAll" value="Reset"
onClick="UnCheckAll(document.gamesettings.gamesetting)">
</form>
<br />
<br />
<div id="boardgames">
<div class="1p 2p 15m 30m" style="display: block;">1p 2p 15m 30m</div>
<div class="1p 2p 30m 45m" style="display: block;">1p 2p 30m 45m</div>
<div class="2p 30m 60m" style="display: block;">2p 30m 60m</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input[name=gamesetting]').change(function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(".")
var str = (".") + vals
$('#boardgames div').hide();
$('#boardgames div' + (str)).show();
})
function UnCheckAll(chk) {
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
$('#boardgames div').show();
}
</script>
</body>
</html>

Related

Another way to show and hide buttons

The following codes works with no problem if I am running the file locally on my drive. Unfortunately, I need to upload this form to a software called MasterControl. It does not work. I was wondering if there is another way of coding that is universal to local as well as upload to a server for MasterControl.
The purpose of this code is - once you click on Yes button on the first level question then the next level questions will appear. If you click on No button on the first level and if the questions from the next level questions showing then it will clear all the selected buttons and hide the section of the second level questions.
Here is the codes:
HTML Code:
<div id="divDeathOccurred" class="fieldRow">
<div class="leftLabel labelWidth22">
<label for="">A. Has a death occurred?</label>
</div>
<div class="leftField">
<div class="formField34">
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="Yes" onclick="javascript:USAYesNoCheckDO();" />Yes
<input id="rbDeathOccurred" name="rbDeathOccurred"
type="radio" class="radiobuttonfield" title="Death Occurred"
value="No" onclick="javascript:USAYesNoCheckDO();" />No
</div>
</div>
<p> </p>
<div id="USADOYesNo" style="display:none">
<ol type="1" class="indentList">
<li>Is there a reasonable possibility that a device failure
or malfunction was a direct or indirect factor in the death?
<br>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceFailure30Days();" />
<label for="rbDOYesNo" class="rptColor">Yes -
reportable</label>
<input id="rbDOYesNo" name="rbDOYesNo" type="radio"
class="USDO1 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceFailure30Days();" />No - No
Report
<div id="calc" class="indentListCalc">
<input id="dt30Days3" type="text" class="textfieldCalc
labelWidth25" alt="Device Malfunction" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that a device design
defect was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO2 radiobuttonfield" title="Yes Reportable" value="Yes"
onclick="javascript:USDeviceDesign30Days();"/>
<label for="rbDOYesNo1" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo1" name="rbDOYesNo1" type="radio"
class="USDO3 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceDesign30Days();" />No - No Report
<div id="calc1" class="indentListCalc">
<input id="dt30Days1" type="text" class="textfieldCalc
labelWidth25" alt="Device Design" />
</div>
<p></p>
</li>
<li>Is there a reasonable possiblity that the device
labeling was direct or indirect factor in the death?
<br>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO4 radiobuttonfield" title="Yes Reportable"
value="Yes" onclick="javascript:USDeviceLabeling30Days();"/>
<label for="rbDOYesNo2" class="rptColor">Yes -
Reportable</label>
<input id="rbDOYesNo2" name="rbDOYesNo2" type="radio"
class="USDO5 radiobuttonfield" title="No" value="No"
onclick="javascript:USDeviceLabeling30Days();"/>No - No Report
<div id="calc2" class="indentListCalc">
<input id="dt30Days2" type="text" class="textfieldCalc
labelWidth25" alt="Device Labeling" />
<p></p>
</div>
</li>
</ol>
</div>
</div> <!-- final section Death Occurred end -->
Javascript Code:
function USAYesNoCheckDO() {
if (document.getElementById('rbDeathOccurred').checked) {
document.getElementById('USADOYesNo').style.display = 'block';
} else {
document.getElementById('USADOYesNo').style.display = 'none';
document.getElementsByClassName('USDO')[0].checked = false;
document.getElementsByClassName('USDO1')[0].checked = false;
document.getElementById('calc').style.display = 'none';
document.getElementsByClassName('USDO2')[0].checked = false;
document.getElementsByClassName('USDO3')[0].checked = false;
document.getElementById('calc1').style.display = 'none';
document.getElementsByClassName('USDO4')[0].checked = false;
document.getElementsByClassName('USDO5')[0].checked = false;
document.getElementById('calc2').style.display = 'none';
}
}
I am still learning about all of this HTML, Javascript, and I am just getting into JQuery.
If you need me to put these codes in jsfiddle, please let me know.
Thank you so much,
IreneS
Update:
I forgot to add that the codes work on the server when you select the buttons and the show and hide - the one thing does not work is the clearing the selected buttons.
Thank you again.
Update 2:
After many hours of research and trying to learn Jquery, hoping that it will give me another way to get this issue resolved and get it to work on the server, unfortunately it did not. The reason I was trying Jquery, because I was looking at the other forms that were on the MasterControl server, and they were coded with Jquery. Unfortunately, being a beginner in Jquery, I am not able to get it to work on both sides - the local drive and the server. Please can someone check it and see what I am missing or doing wrong.
function getChecked(radioGroupName, index)
{
var oRadioList = document.getElementsByName(radioGroupName);
return oRadioList[index].checked;
}
function setChecked(radioGroupName, index, state)
{
var oRadioList = document.getElementsByName(radioGroupName);
oRadioList[index].checked = state;
}
function USAYesNoCheckDO()
{
if(getChecked("rbDeathOccured",0) == true)
{
$('#USADOYesNo').slideDown(1000);
}
else
{
$('#USADOYesNo').slideUp(1000);
setChecked("rbDOYesNo",0,false);
setChecked("rbDOYesNo",1,false);
setChecked("rbDOYesNo1",0,false);
setChecked("rbDOYesNo1",1,false);
setChecked("rbDOYesNo2",0,false);
setChecked("rbDOYesNo2",1,false);
}
}
Or if you have any idea how to get this issue fixed. As I mentioned before the buttons work and the show and hide of the questions work, the issue is when I want to reset and set it back to the original status - blank.
Thank you again and appreciate any help.
IreneS
Update 3:
Please anybody have any thoughts/ideas on how to fix this issue.
I really appreciate any help.
Thank you,
IreneS
Update 4:
Just incase someone have the same issue as I am and need a solution, I finally found a website after all this time of searching that gave me the answer and it works! Yeh! I just customized the coding to my needs and it works locally and on the server.
http://www.electrictoolbox.com/javascript-clear-form/
IreneS.
You use the same id attribute for multiple elements. id should be unique on the page, only name can be the same to group multiple input elements of the same type. I don't know if this is the main problem but it is a start.

Different way to generate divs via checkbox

Currently I am using the below method using JS to generate a block of text in a right column when a check box is clicked ticked in a left column.
This has been working fine, however each time I need to add a check box, I need to add a new class and new formContainer element. With the original 3 I had, wasn't a big deal. But now that I'm up to 10 and growing, getting a bit cumbersome.
What better possibilities exist to generate a div/block of text on a different part of the page as a result of a ticked check box?
Check Box
<input id="chk" data-detail="<br>Right 1" class="chkbox" type="checkbox" value="results" />1
Creating individual class
<div class="formContainer"></div>
Script
<script>
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
}
else
{
$('.formContainer').html('');
}
});
</script>
If you are wanting them in columns you can generate them using bootstrap gridsystem.
<div class="formContainer>
<div class="container">
<div class="row">
<div class="col-m-4"></div>
<div class="col-m-4"></div>
<div class="col-m-4"></div>
</div>
<div class="row">
...
</div>
</div>
</div>
If you are wanting to keep them in the same column you could just use .append()
$('.formContainer').append('<div class="new">'+$(this).data('detail')+'</div>');
These can be used together to generate a fluid system or just the append can be used to keep adding divs to your formContainer
I would suggest appending a form after your checkbox using the Jquery function .after(newElement);
Play with it on codepen
Html:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<style>
.formContainer{
height: 50px;
width: 100%;
background-color: gray;
}
</style>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
JQuery:
$(document).ready(function(){
$('.checkboxesThatAppends').click(function(){
var associatedFormId = $(this).attr('data-associated-form-id');
if(associatedFormId){
//if there is a form container associated with this checkbox already
//then let's remove that form.
//and remove the association from the checkbox
$('#'+associatedFormId).remove();
$(this).attr('data-associated-form-id', '');
}else{
//generate an Id for the new form to attach.
var newId = new Date().getTime();
$(this).attr('data-associated-form-id', newId);
$(this).parent().after('<div id="'+newId+'" class="formContainer"></div> ');
}
});
});
You can just use jQuery's append() and remove() methods in combination with wrapping HTML elements to achieve this effect.
JSFiddle: https://jsfiddle.net/xuc4tze0/1/
HTML
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 1" class="chkbox" type="checkbox" value="results" />1
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 2" class="chkbox" type="checkbox" value="results" />2
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 3" class="chkbox" type="checkbox" value="results" />3
</div>
</div>
CSS
.row {
display: flex;
width: 400px;
}
.left, .right {
flex: 0 0 50%;
}
Javascript / jQuery
$('.chkbox').on('click', function() {
if ($(this).is(':checked'))
// Find the row and add the 'right' column
$(this).closest('.row').append('<div class="right">' + $(this).data('detail') + '</div>');
} else {
// Find the 'right' column and remove it
$(this).closest('.row').find('.right').remove();
}
});
Depending on your need and the content of the divs I got a couple of suggestions :
Modal popups. If you these divs are just notifications then a popup would do (but doubt this is what you need).
List group, use bootstrap's neat class list group to show the needed info in an <ul> element, the JS that comes with these can be neat as well with special animations.
Use tooltips on each checkbox instead of getting a whole div appearing.
Last suggestion which I like least is putting all of your div's in a single container div on the right. Fix its width and height and set overflow attribute so you can scroll up and down the shown divs

jQuery: How to show a checkbox value on mouseover (without title attribute)

I am pretty new to jQuery and need some help with the following.
I have a HTML page with a large, dynamic number of checkboxes and would like to show a checkbox' value on mouseover without having to add a title attribute in the code for each of them.
Also, the value of a checkbox can be different to the text that is shown next to her (label).
The checkboxes are always in a div with the class '.divCheck' and the above applies to all checkboxes in these divs (all set up the same way).
So far I have the following which works as intended but seems to be very slow (at least in my test environment).
Is there a faster / better way to achieve this or can this be written different (either the jQuery or the HTML) to make it run faster ?
My HTML (simplified):
<div class="divCheck">
<input type="checkbox" name="language" class="checkSingle" id="language1" value="de - German" />
<label for="language1">de</label>
<input type="checkbox" name="language" class="checkSingle" id="language2" value="en - English" />
<label for="language2">en</label>
<input type="checkbox" name="language" class="checkSingle" id="language3" value="es - Spanish" />
<label for="language3">en</label>
<!-- ... -->
</div>
My jQuery:
$('div.divCheck label').on('mouseover', function(){
var checkID = $(this).attr('for');
var checkVal = $('#'+checkID).val();
$(this).prop('title', checkVal);
});
Many thanks for any help,
Mike
There is no need to use an event handler, you can set the title programatically like
$('div.divCheck label').attr('title', function(){
return $(this).prev('input').val()
});
$('div.divCheck label').attr('title', function() {
return $(this).prev('input').val()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="divCheck">
<input type="checkbox" name="language" class="checkSingle" id="language1" value="de - German" />
<label for="language1">de</label>
<input type="checkbox" name="language" class="checkSingle" id="language2" value="en - English" />
<label for="language2">en</label>
<input type="checkbox" name="language" class="checkSingle" id="language3" value="es - Spanish" />
<label for="language3">en</label>
</div>
You can set the title attribute of the checkbox to value. By this, you don't need any library/plugin.
$(':checkbox').prop('title', function() {
return $(this).val();
});
Demo: https://jsfiddle.net/zstupsbc/
a tooltip library such as qtip could help you

Input value and div's innerHTML are changed with Javascript but don't change in display

I have an INPUT text field, a DIV and an IMG.
The IMG has an onClick event:
reads the INPUT field's current value,
increase it with 1,
does a calculation with the increased value,
writes the result into the DIV.
The value of the INPUT is always increased the right way and the DIV's innerHTML always gets the right result but nothing changes in display. The displayed numbers always stay the same even if everything is done correctly in the "background".
The funny thing in it that I used the same operation at another place on the same site and there everything works and displays perfectly.
Here is the function:
function priceCalculator(max_amound,price,id)
{
var amound = parseInt(document.getElementById('sell_amound_' + id).value);
max_amound = parseInt(max_amound);
if (amound < max_amound)
{
amound = amound + 1;
document.getElementById('sell_amound_' + id).value = amound;
var item_value = amound * price;
document.getElementById('price_' + id).innerHTML = item_value;
alert(document.getElementById('sell_amound_' + id).value + ',' + document.getElementById('price_' + id).innerHTML);
}
}
And here are the elements within a PHP code:
<img src="images/plus.png" onclick="priceCalculator(\''.$bag_items[$i]['amound'].'\',\''.$bag_items[$i]['infos']['price'].'\',\''.$i.'\')" />
<form>
<input id="sell_amound_'.$i.'" type="text" readonly value="1" />
</form>
<div id="price_'.$i.'">'.$bag_items[$i]['infos']['price'].'</div>
The alert at the end of the function shows the right values but the displayed values stay the same.
It's a really simple action... What could be the problem?
EDIT:
After loading the source code of an "item" looks like this (these parts are created with loops from database, and, of course, I removed the irrelevant styling from the code and those many divs are there because of them):
<td>
<img id="item_pic_3" src="images/potions/3.png" onClick="shopSellInfo('3')" />
<div>26</div>
<form>
<input type="hidden" id="selected_item" value="" />
</form>
<div id="item_3" style="display: none;">
<span>blah...</span><br />
<span>
<br />blah...<br /><br />
<div>
<div>
<img src="images/increase.png" onclick="priceCalculator('26','10','3')" /><br />
</div>
<div>
<form>
<input id="sell_amound_3" type="text" readonly value="1" />
</form>
/26
</div>
</div>
<br />
<div id="price_3">10</div>
</span>
</div>
</td>
shopSellInfo('3') is the function that makes item_3 displayed at the right place.
Can you please view source and show what is output by:
<div id="price_'.$i.'">'.$bag_items[$i]['infos']['price'].'</div>
Check that the div id is corresponding to the JavaScript's.
EDIT: item_3 has CSS style display: none, that is why changes are not showing up.
I solved the problem!
The problem was that the IDs appeared at another place, too, so the function didn't know where to change the values because of the duplicated IDs.
Anyway, thanks your answers and will for help!

Using javascript and html to show images when checkboxes are checked

I'm trying to create a page that generates simple custom reports based on the checkboxes a user clicks. On the left side I will have a vertical column of checkboxes. For simplicity's sake, lets say I have two checkboxes labeled "Population" and "Employment".
When a user is interested in seeing employment data they check the "Employment" box and the image file of the data "employment.jpg" will be displayed to the right. If they then uncheck the box, the image will disappear. If they check both boxes, both images will be similarly displayed, one below the other in the order clicked.
I'm am loosely familiar with HTML, and new to Javascript. I've been trying to do this with if statements and document.write but can't keep my checkboxes on the page when the image is generated.
Here's my current code:
<html>
<head>
<script language="javascript" type="text/javascript">
function checker(that) {
if (that.checked) {
document.write("<br /><br /><img src='employment.png'>");
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="Box" onclick="checker(this)"> Employment <br />
</form>
</body>
</html>
Here's a quick example to get you started. You can see it in action here.
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>
<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation" onChange="toggleVisibility('imgpopulation');" />
<hr />
<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden"/>
<img id="imgpopulation" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden" />
This is how the solution looks like in AngularJS:
<script src="http://docs-next.angularjs.org/angular-0.10.1.min.js"
ng:autobind></script>
<p>
<input type="checkbox" name="production" id="production" />
<label for="production">Production</label>
</p>
<p>
<input type="checkbox" name="employment" id="employment" />
<label for="employment">Employment</label>
</p>
<img src="http://i.i.com.com/cnwk.1d/i/bto/20071106/OLPC_photo_540x360.jpg"
ng:show="production" />
<img src="http://www.sunriseenterprisesinc.com/main/Portals/0/EmploymentSmall.jpg"
ng:show="employment" />
You can play with the example here: http://jsfiddle.net/psyho/nrdnx/
You can handle the change event of the checkboxes. Here's a full example (without images, though): http://jsfiddle.net/minitech/hsF9s/
Usually people use a framework such as jQuery. It allows you to abstract away from the nitty gritty details and cross-browser pains. Using that, you would do the task you describe like this:
http://jsfiddle.net/3vQJZ/3/
And here's the code from that working demo:
<input type="radio" name="selectPicture" value="http://i170.photobucket.com/albums/u277/AmandaisAwesomeQUACK/monkey.gif"/>
<input type="radio" name="selectPicture" value="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" checked/>
<img id="image" src="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" alt="image selected by radio buttons"/>
$(document).ready(function(){
$('input[name=selectPicture]').click(function(){
$('#image').attr('src', $('input[name=selectPicture]:checked').val());
});
});

Categories