Click on submit button after drag and drop - javascript

I have the following code:
<div id="main" style="width: 500px; height: 500px; background: #ddd; float: left;"></div>
<div id="list" style="width: 200px; height: 500px; border: 1px solid #ddd; float: left; margin-left: 15px;">
<div class="section">
Ja/Nej
<div class="showforms" style="display: none;">
<strong>Fritext</strong>
<input type="text" name="question">
<p><input type="radio" name="test" value=1> Ja<br>
<input type="radio" name="test" value=0> Nej<br></p>
<input type="submit" name="save" value="Spara" class="save">
</div>
</div>
<div class="section">
Option list
<div class="showforms" style="display: none">
<select>
<option>Fisk</option>
<option>Fisk2</option>
</select>
</div>
</div>
</div>
$(document).ready(function() {
var jsonObj = [];
var i = 0;
$('.section').draggable({
revert: "invalid",
stack: ".yesorno",
helper: "clone"
});
$('#main').droppable({
accept: ".section",
drop: function(event, ui) {
//Lagra ui-objektet i en lista
//Loopa ut objekten och sätt ett index på varje classnamn och visa input fältet
jsonObj[i] = {"Objekt": ui.draggable, "Id": i};
var draggable = jsonObj[i]["Objekt"];
var droppable = $(this);
draggable.show('.showforms');
draggable.clone().appendTo(droppable);
$("#main").find("div").attr('id', i).show();
var testa = $('#main').find("div")[i];
var submit = $(testa).find(":submit").attr('test', i);
console.log($(testa).find(":submit"));
//Object[div#yesorno.ui-draggable.ui-draggable-handle]
i++;
}
});
});
$('.save').click(function() {
console.log("hej"); //This don't work
});
The thing I'm doing here is that I take a section-div containing some input-fields that is being hidden. I drag this into the main-div and drop it here. After it has been dropped, the input-fields are shown.
The problem I have is that nothing is printed out when I click on the submit button after I have dragged and dropped it in the Main-div. What am I doing wrong?

I solved It by doing this:
$(document).on('click', ".save", function() {
console.log($(this).attr('test'));
});

Try:
Replace
<input type="submit" name="save" value="Spara" class="save">
With
<input type="submit" name="save" value="Spara" class="save" onClick="saveFunction()">
Replace
$('.save').click(function() {
console.log("hej"); //This don't work
}
With
function saveFunction(){
console.log("hej");
}

Related

How do I make the second div have the same height as first div, irrespective of the screen-width?

I want my two divs to be of equal height regardless of the device used to view the page. To ensure this, I wrote the js function below:
window.onload = function() {
var left=document.getElementsByClassName('bg-text')[0].clientHeight;
var right=document.getElementsByClassName('para')[0].clientHeight;
if(left>right) {
document.getElementsByClassName('para')[0].style.height=left+"px";
}
else{
document.getElementsByClassName('bg-text')[0].style.height=right+"px";
}
};
The code above works for most cases, not all. As I keep on reducing the screen width from the console, the second div becomes larger than the first div. How do I fix this?
**EDIT: ** This is my html:
<div class="bg-text">
<h4><u>Newspaper particulars</u></h4><br>
<ul>
<li><label for="date">Select date :</label><br></li>
<input type="date" id="date" name="date" style="text-align: center; width: 100%;"><br><br>
<li><label for="news">Select newspaper :</label><br></li>
<select name="news" id="news" style="text-align: center; width: 100%;">
<option value="default">Click to select</option>
<option value="The Assam Tribune">The Assam Tribune</option>
<option value="The Times of India">The Times of India</option>
<option value="The Hindu">The Hindu</option>
<option value="Hindustan Times">Hindustan Times</option>
<option value="The Telegraph">The Telegraph</option>
</select><br><br>
<li><label for="paragraph_text" id="para">Subject description :</label><br></li>
<textarea name="paragraph_text" id="paragraph_text" rows="3" style="resize: none; box-sizing:border-box; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box;"></textarea><br><br>
<span>Choose the required mode of input</span>
<li><div class="mb-3" style="width: 100%; border: 2px solid white; padding: 10px;">
<input type="radio" id="sel_scan" name="doc" value="scanning">
<button id="scan" onclick="startScan()" disabled>Scan document</button><br><br>
<div style="width: 100%;">
<input type="radio" id="myfile" name="doc" value="choosing">
<input type="file" id="Myfile" accept=".pdf,.jpg,.png" disabled>
</div>
</div></li>
</ul>
</div>
<div class="para">
<div class="container">
<span id="preview_text" style="text-align: center; vertical-align: middle; line-height: 400px; color: red;">Choose/Scan file to see preview here</span>
</div>
</div>
I want both the divs bg-text and para be of equal heights. Infact, as the second div is empty, so I want it to be the same height as that of the first div
You need to adjust the heights on resize as well. The code below should work:
function setHeight() {
var leftElement = document.getElementsByClassName('bg-text')[0];
var rightElement = document.getElementsByClassName('para')[0];
// Reset height
leftElement.style.height = "auto";
rightElement.style.height = "auto";
var leftHeight = leftElement.offsetHeight;
var rightHeight = rightElement.offsetHeight;
// Get max height and set it for both divs
var maxHeight = Math.max(leftHeight, rightHeight);
leftElement.style.height = maxHeight+"px";
rightElement.style.height = maxHeight+"px";
}
window.onload = function() {
setHeight();
};
window.onresize = function() {
setHeight();
}

Clone div and delete div

I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
function appearafter2() {
document.getElementById("buttonappear2").style.display = "block";
document.getElementById("button2").style.display = "block";
document.getElementById("hinzufuegen2").style.display = "none";
}
function myFunction2() {
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList3").appendChild(cln);
}
function deleteFunction2() {
var list3 = document.getElementById("myList3");
var divs = Array.from(list3.getElementsByTagName("div"));
// If the number of divs is 4, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 4) {
document.getElementById("button2").style.display = "none";
}
var lastDivToDelete2 = divs[divs.length - 1];
list3.removeChild(lastDivToDelete2);
}
function allFunction2() {
myFunction2();
appearafter2();
}
#button2 {
display: none;
}
#buttonappear2 {
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#myList3 {
display: none;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="allFunction2()">
+ Loc de munca
</div>
<div id="myList3">
<div id="button2" onclick="deleteFunction2()">Șterge</div>
<div id="myList4">
<div id="addingNewJob">
<label class="label-job-input" for="job-input-1">Numele firmei</label>
<select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
<option value="scoala">școală profesională</option>
<option value="lic">liceu</option>
<option value="fac">facultate</option></select>
<label class="label-job-input" for="job-input-2">Postul ocupat
</label>
<input size="1" type="text" id="job-input-3" /><br />
<label class="label-data2" for="job-input-3">din data</label><label class="label-data2" for="job-input-4">până la data</label><br />
<input type="number" style="width: 48%" />
<input type="number" style="width: 50%; margin-left: 6px" />
</div>
</div>
</div>
<div onclick="allFunction2()" id="buttonappear2">
+ Loc de munca
</div>
Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
Updated the answer, check if this is what you are trying to achieve.
function myFunction2() {
var cln = '<div class="list-item">'+
'<div id="addingNewJob">'+
'<label class="label-job-input" for="job-input-1">Numele firmei</label>'+
'<select size="1" type="text" id="job-input-1" /></div>';
document.getElementById("myList3").innerHTML+=cln;
document.getElementById("buttonappear2").classList.remove('hide');
document.getElementById("button2").classList.remove('hide');
document.getElementById("hinzufuegen2").classList.add('hide');
}
function deleteFunction2() {
var divs = Array.from(document.querySelectorAll(".list-item"));
if(divs.length>0){
var lastDivToDelete2 = divs[divs.length - 1];
document.getElementById("myList3").removeChild(lastDivToDelete2);
}
if(divs.length==1){
document.getElementById("buttonappear2").classList.add('hide');
document.getElementById("button2").classList.add('hide');
document.getElementById("hinzufuegen2").classList.remove('hide');
}
}
.hide{
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="myFunction2()">+ Loc de munca</div>
<div id="myList3">
<div id="button2" class="hide" onclick="deleteFunction2()">Șterge</div>
</div>
școala generală școală profesională liceu facultate
<label class="label-job-input" for="job-input-2">Postul ocupat</label>
<form>
<input size="1" type="text" id="job-input-3" />
<br />
<label class="label-data2" for="job-input-3">din data</label>
<label class="label-data2" for="job-input-4">până la data</label>
<br />
<input type="number" style="width: 48%;" />
<input type="number" style="width: 50%; margin-left: 6px;" />
</form>
<div onclick="myFunction2()" class="hide" id="buttonappear2">+ Loc de munca</div>

Jquery fuction on multiple elements

As you can see in the Snippet code below, I have two buttons and one input for each container. Now, The input calc and sums up the number of clicks on the 2 buttons in the same container. But, it's only working for the first container. How can I make it work for each container separately without setting an ID for each group of inputs?
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.click').click(function() {
var val1 = +$('.val1').val();
var val2 = +$('.val2').val();
$('.count').val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
First get the parent of the clicked element, then search for the .valx elements only within this parent.
$('.click').click(function (e) {
var $parent = $(e.currentTarget).parent();
var val1 = +$parent.find('.val1').val();
var val2 = +$parent.find('.val2').val();
$parent.find('.count').val(val1 + val2);
});
This way, you can have as many counters as you want.
Update:
You can also add the +1 feature in the same click event. Like so:
$('.click').click(function (e) {
var $input = $(e.currentTarget);
var $parent = $input.parent();
// Value ++
$input.val($input.val() + 1);
// Set the total count
var val1 = +$parent.find('.val1').val();
var val2 = +$parent.find('.val2').val();
$parent.find('.count').val(val1 + val2);
});
Got it working for you!
Use $(this).parent().find();
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.click').click(function() {
var val1 = + $(this).parent().find('.val1').val();
var val2 = + $(this).parent().find('.val2').val();
$(this).parent().find('.count').val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
Here is the Solution for You:
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.val1').click(function() {
var val1 = +$(this).val();
var val2 = +$($(this).siblings('.val2')).val();
$($(this).siblings('.count')).val(val1+val2);
});
$('.val2').click(function() {
var val1 = +$($(this).siblings('.val1')).val();
var val2 = +$(this).val();
$($(this).siblings('.count')).val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>

Replicating entries and XML with JavaScript

I'm building a user-submission system where a user can input data and an XML will be exported (which can be read by a different software down the line) but I'm coming across a problem where when I replicate the form for the user to input info, the XML is only taking information from the first.
Any suggestions on how do this?
Personal test code:
HTML:
$(function () {
$('#SubmitButton').click(update);
});
var added = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
var adding = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
function update() {
var variables = {
'channeldescription': $('#channeldescription').val(),
'channelrecordnumber': $('#channelrecordnumber').val(),
'channelhexcolor': $('#channelhexcolor').val(),
'channelbamlink': $('#channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
var finalXML = newXml;
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
added = added + '\n' + adding;
$("body").append($("#Entries:first").clone(true));
}
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<body>
<div id="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea id="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input id="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input id="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">RNA-Seq Data/BAM file Repsitory Link</label>
<input id="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly></textarea>
</div>
</div>
</html>
http://www.w3schools.com/code/tryit.asp?filename=F0TWR6VRQZ3J
Change your ids to classes use a loop to get all the entries
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
.leftmargin {
margin-left: 2%;
}
.form {
background-color: #CBE8BA;
border-radius: 25px;
margin-left: 2%;
margin-right: 2%;
padding-top: 1%;
padding-bottom: 1%;
}
.forminput {
padding-left: 1.5%;
padding-top: 0.5%;
display: flex;
}
.button_fixed {
position: fixed;
margin-left: 2%;
bottom: 1%;
}
</script>
<script>
$(function () {
$('#SubmitButton').click(function(){
var finalXML = '';
$(".Entries").each(function(i,v) {finalXML +=update(finalXML,v)
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
});
});
});
var added = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
var adding = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
function update(finalXML,v) {
var variables = {
'channeldescription': $(v).find('.channeldescription').val(),
'channelrecordnumber': $(v).find('.channelrecordnumber').val(),
'channelhexcolor': $(v).find('.channelhexcolor').val(),
'channelbamlink': $(v).find('.channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
return newXml;
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
$("body").append($(".Entries:first").clone(true));
}
</script>
<body>
<div class="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea class="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input class="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input class="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">BAM file Repsitory Link</label>
<input class="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly="readonly"></textarea>
</div>
</div>
</html>
demo:http://www.w3schools.com/code/tryit.asp?filename=F0TXIUR1CYE4

How to link a checkbox(:checked) to a class?

I have setup a filter list which checkboxes. When the specific checkbox is checked, i need to interact with a class so it hides through JavaScript. Also, if multiple checkboxes are checked, i need to show these items with both the classes. I have this:
HTML:
<div class="categs" id="filters">
<div class="categhead">
<p>Ranking</p>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;">
<label for="tagchallenger">Challenger</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;">
<label for="tagmaster">Master | Diamond</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;">
<label for="tagplat">Platinum | Gold</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;">
<label for="tagsilver">Silver | Bronze</label>
</div>
<script type="text/javascript">
[].forEach.call(document.querySelectorAll('.hide-checkbox'), function(element) {
element.style.display = 'none';
});
</script>
</div>
JavaScript:
var streameach = $('.streampic .row .col-md-4');
function updateContentVisibility(){
var checked = $('#filters :checkbox:checked');
if(checked.length){
streameach.hide();
checked.each(function() {
$("." + $(this).val()).show();
});
} else {
streameach.show();
}
}
$('#filters :checkbox').click(updateContentVisibility);
updateContentVisibility();
}
And then i also have
<div class="streamtag1">...</div>
And
var stream0 = "<? echo $lolarray->streams[0]->channel->name; ?>";
if (stream0 == "riotgames") {
$('streamtag1').addClass('master');
};
Now when the checkbox 'master' is clicked, it hides all the divs, but doesn't show the ones that have the added master class,which should be connected to that checkbox.
I would set it up like the below:
Here's a jsFiddle
function updateContentVisibility() {
$('.hide-checkbox').each(function () {
if ($(this).is(':checked')) {
$('.' + $(this).val()).hide();
} else $('.' + $(this).val()).show();
});
}
$('.hide-checkbox').change(function () {
updateContentVisibility();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagriot" value="riot">
<label for="tagriot">RIOT</label>
<input class="hide-checkbox" type="checkbox" id="tagblue" value="blue">
<label for="tagblue">blue</label>
<input class="hide-checkbox" type="checkbox" id="taggreen" value="green">
<label for="taggreen">green</label>
<input class="hide-checkbox" type="checkbox" id="tagred" value="red">
<label for="tagred">red</label>
</div>
<div class="riot">riot</div>
<br>
<div class="blue">blue</div>
<br>
<div class="green">green</div>
<br>
<div class="red">red</div>
<br>
Given the question description, and some clarification in the comments to that question, I'd suggest the following approach, using jQuery:
// selecting the <input> elements of class-name 'hide-checkbox',
// binding an anonymous function to handle the 'change' event:
$('input.hide-checkbox').on('change', function () {
// selecting all elements whose class-name is equal to the
// <input> element's value, and using the toggle(switch)
// approach, to show if the switch is true (the checkbox is checked)
// and hide if the switch is false (the checkbox is unchecked):
$('.' + this.value).toggle(this.checked);
// triggering the change event, so that the function runs on page-load,
// to hide/show as appropriate:
}).change();
[].forEach.call(document.querySelectorAll('.hide-checkbox'), function(element) {
element.style.display = 'none';
});
$('input.hide-checkbox').on('change', function() {
$('.' + this.value).toggle(this.checked);
}).change();
label {
cursor: pointer;
}
input:checked + label {
color: #f90;
}
#contents div[class] {
border: 1px solid #000;
border-radius: 1em;
padding: 0.5em;
margin: 0 auto 0.5em auto;
width: 80%;
}
#contents div[class]::before {
content: attr(class);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="categs" id="filters">
<div class="categhead">
<p>Ranking</p>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;" />
<label for="tagchallenger">Challenger</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;" />
<label for="tagmaster">Master | Diamond</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;" />
<label for="tagplat">Platinum | Gold</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;" />
<label for="tagsilver">Silver | Bronze</label>
</div>
</div>
<div id="contents">
<div class="challenger"></div>
<div class="master"></div>
<div class="plat"></div>
<div class="silver"></div>
</div>
External JS Fiddle demo, for experiementation.
Or, with plain JavaScript:
// creating a named function to handle the show/hide functionality:
function toggleView() {
// a cached reference to the changed <input>:
var control = this,
// a reference to whether the <input> is checked or not:
check = control.checked,
// retrieving all elements with a class-name equal to the
// <input> element's value:
targets = document.querySelectorAll('.' + control.value);
// using Array.prototype.forEach(), with Function.prototype.call(),
// to iterate over the found elements:
Array.prototype.forEach.call(targets, function (node) {
// setting the display property of each found-element's
// style property; if the checkbox is checked we set
// the display to 'block', if not we set it to 'none':
node.style.display = check ? 'block' : 'none';
});
}
// creating a 'change' event so that we can trigger the function
// to run on page-load:
var changeEvent = new Event('change');
// As above, iterating over the '.hide-checkbox' elements:
Array.prototype.forEach.call(document.querySelectorAll('.hide-checkbox'), function (element) {
// hiding the elements:
element.style.display = 'none';
// binding the named function (toggleView)
// to handle the change event:
element.addEventListener('change', toggleView);
// triggering the change event on each of the
// '.hide-checkbox' elements:
element.dispatchEvent(changeEvent);
});
function toggleView() {
var control = this,
check = control.checked,
targets = document.querySelectorAll('.' + control.value);
Array.prototype.forEach.call(targets, function (node) {
node.style.display = check ? 'block' : 'none';
});
}
var changeEvent = new Event('change');
Array.prototype.forEach.call(document.querySelectorAll('.hide-checkbox'), function (element) {
element.style.display = 'none';
element.addEventListener('change', toggleView);
element.dispatchEvent(changeEvent);
});
label {
cursor: pointer;
}
input:checked + label {
color: #f90;
}
#contents div[class] {
border: 1px solid #000;
border-radius: 1em;
padding: 0.5em;
margin: 0 auto 0.5em auto;
width: 80%;
}
#contents div[class]::before {
content: attr(class);
}
<div class="categs" id="filters">
<div class="categhead">
<p>Ranking</p>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;" />
<label for="tagchallenger">Challenger</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;" />
<label for="tagmaster">Master | Diamond</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;" />
<label for="tagplat">Platinum | Gold</label>
</div>
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;" />
<label for="tagsilver">Silver | Bronze</label>
</div>
</div>
<div id="contents">
<div class="challenger"></div>
<div class="master"></div>
<div class="plat"></div>
<div class="silver"></div>
</div>
External JS Fiddle demmo for experiementation/development.
References:
JavaScript:
Array.prototype.forEach().
document.querySelectorAll().
Event() constructor.
EventTarget.addEventListener().
Event.target.dispatchEvent().
Function.prototype.call().
jQuery:
change().
on().
toggle().

Categories

Resources