Alright, I've gone through lot of sources but I've got confused applying them all. I'm new to javascript and jquery.
I have a step by step choices (i got a wizard template). So I wanted to display a text field from the previous step/div when "wedding" radio button is checked.
my html code:
<div id="step-1">
<fieldset>
<input type="radio" id="theme1" name="cake_theme" value="wedding" onchange="see()" />
<input type="radio" id="theme2" name="cake_theme" value="bday" onchange="see()" />
<input type="radio" id="theme3" name="cake_theme" value="occassion" onchange="see()" />
</fieldset>
</div>
<div id="step-2">
Date: <input type="date" name="date_pick"/> //remains
<div class="wed_delivery"> Venue : <input type="text" name="wed_delivery" placeholder="Venue to Delivery"/> //only shows up when "wedding button" is checked
</div>
</div>
<div id="themedisplay" height="100px" width="300px"> </div>
I have in my JS in different file: (working fine)
function see(){
var canvas = document.getElementById('displaycake');
if (document.getElementById('theme1').checked) {
document.getElementById('themedisplay').innerHTML = "Wedding Cake";
}
if (document.getElementById('theme2').checked) {
document.getElementById('themedisplay').innerHTML = "Birthday Cake";
}
if (document.getElementById('theme3').checked) {
document.getElementById('themedisplay').innerHTML = "Occassion Cake";
}
}
I tried putting below the div "step-1"
<script>
$(document).ready(function () {
$(".wed_delivery").hide();
$("#theme1").click(function () { //theme1 is the Wedding Theme
$(".wed_delivery").show();
});
</script>
It doesn't work, is it possible in a Wizard Template?
Thanks in advance, comments each line are appreciated.
This will help you. Point to note.
1: Close your document.ready function properly.
2: Include JQuery if not included.
3: Bind the event with radio buttons and hide/show the text box if the checked radio is/is not wedding radio button
function see(){
var canvas = document.getElementById('displaycake');
if (document.getElementById('theme1').checked) {
document.getElementById('themedisplay').innerHTML = "Wedding Cake";}
if (document.getElementById('theme2').checked) {
document.getElementById('themedisplay').innerHTML = "Birthday Cake";}
if (document.getElementById('theme3').checked) {
document.getElementById('themedisplay').innerHTML = "Occassion Cake";}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="step-1">
<fieldset>
<input type="radio" id="theme1" name="cake_theme" value="wedding" onchange="see()" />
<input type="radio" id="theme2" name="cake_theme" value="bday" onchange="see()" />
<input type="radio" id="theme3" name="cake_theme" value="occassion" onchange="see()" /> </fieldset> </div>
<div id="step-2">
Date: <input type="date" name="date_pick"/> //remains
<div class="wed_delivery"> Venue : <input type="text" name="wed_delivery" placeholder="Venue to Delivery"/> //only shows up when "wedding button" is checked </div>
</div>
<div id="themedisplay" height="100px" width="300px"> </div>
<script>
$(document).ready(function () {
$(".wed_delivery").hide();
$("input[type='radio']").click(function () { //theme1 is the Wedding Theme
if($(this).val() == "wedding")
{
$(".wed_delivery").show();
}
else
{
$(".wed_delivery").hide();
}
});
});
</script>
Establish 2 classes to represent the status of off and on and assign the textbox the .off class initially. When the change event is triggered, then use .addClass() and .removeClass() jQuery methods.
There are too many changes to OP to explain, so I commented details in the Snippet:
SNIPPET
/* Shorthand for $(document).ready(function() { */
$(function() {
/* change event triggered by any radio button */
$(':radio').on('change', function() {
/* $(this) is the function owner,
| in this case it is the specific
| radio button being changed
*/
// Get radio value
var title = $(this).val();
// Get radio data-img
var img = $(this).data('img');
// Get url of background-image
var path = 'http://imgh.us/' + img;
// Set text of figcaption
$('#themeTitle').text(title);
// Set background-image of figure
$('#themeDisplay').css('background', 'url(' + path + ')no-repeat');
// if the checked radio id is 'theme1'...
if ($(this).attr('id') === 'theme1') {
//...status of textbox is on...
$('.wedDelivery').addClass('on').removeClass('off');
} else {
//...otherwise status of textbox is off
$('.wedDelivery').removeClass('on').addClass('off');
}
});
});
.off {
display: none;
}
.on {
display: inline-block;
}
#themeDisplay {
width: 300px;
height: 100px;
}
#themeTitle {
font: 700 16px/1.4 cursive;
color: black;
background: rgba(255, 255, 255, .6);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id='step1'>
<legend>Event Themes</legend>
<!--data-img represents the image file name can be manipulated by .attr() or .data()-->
<label>Wedding
<input type="radio" id="theme1" name="cakeTheme" value="Wedding" data-img='wedcake.jpg'>
</label>
<label>Birthday
<input type="radio" id="theme2" name="cakeTheme" value="Birthday" data-img='bdaycake.jpg'>
</label>
<label>Special Occasion
<input type="radio" id="theme3" name="cakeTheme" value="Special Occasion" data-img='speccake.jpg'>
</label>
</fieldset>
<fieldset id="step2">
<legend>Pick-up/Delivery</legend>
<label>Date:
<input type="date" name="datePick">
</label>
<label class='wedDelivery off'>Venue :
<input type="text" name="wedDelivery" placeholder="Venue to Delivery">
</label>
</fieldset>
<figure id="themeDisplay">
<figcaption id='themeTitle'></figcaption>
</figure>
Related
I have problem with a code after migrating to jquery 3
NOT WORKING : Need update and need delete ui jquery
I would like migrate to 3.6 but error :
https://jsfiddle.net/alex447/u817ybjk/1/
Working but old version :
https://jsfiddle.net/alex447/c06tb5rL/28/
Having done very little jquery I would like to review the code in the latest jquery version and without ui-query so that the progress bar is displayed.
If you change the code to version 1.5 with ui jquery you can see the final result I want.
If i go to jquery 3.4.1 or other I have error :
"jQuery.Deferred exception: $(...).progressbar is not a function",
"TypeError: $(...).progressbar is not a function
at HTMLDocument.<anonymous> (https://fiddle.jshell.net/_display/?editor_console=true:728:23)
at mightThrow (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js:3534:29)
at process (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js:3602:12)",
undefined
Thanks
You have to add the jQuery ui library , ( knowing that progress() function belong to this last ),
It works on the previous version because the is a checked input that import the ui automatically as you can see here :
add theme + jQuery ui cdn url will resolve the issue as this jsFiddle
But if you want to get rid of the jQuery ui ,
You could create your own progress , some css and simple js ,as shown in the below Snippet :
$(document).ready(function() {
$("#progressbar").css("width",0);
$('[type*=radio]').click(function() {
var totalChecked = 0;
var totalRadioGroups = 0;
var previousName = '';
$.each($('[type*=radio]'), function(index, value) {
var radioName = $(this).attr('name');
var radioId = this.id;
if (previousName != radioName) {
totalRadioGroups++;
}
if ($('#' + radioId).is(':checked')) {
totalChecked++;
}
previousName = radioName;
});
var percentage = (totalChecked / totalRadioGroups) * 100;
$('#progressbar').css('width', percentage+"%");
$('#progressbar').html(percentage.toFixed(2) + "%");
$('#percentage').html(percentage.toFixed(2) + "%");
});
});
#progress-container {
width: 100%;
border: 1px solid #ddd;
height:25px;
border-radius:5px;
overflow:hidden;
}
#progressbar {
height: 25px;
background-color: #0412AD;
text-align: center;
line-height: 30px;
color: white;
width:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Question 1<br>
<div class="js-form-item">
<input type="radio" name="radioQone" id="radioQ11">Option 1<br>
</div>
<div class="js-form-item">
<input type="radio" name="radioQone" id="radioQ12">Option 2<br>
</div>
<div class="js-form-item">
<input type="radio" name="radioQone" id="radioQ13">Option 3<br>
</div>
<br>Question 2<br>
<div class="js-form-item79">
<input type="radio" name="radioQtwo" id="radioQ21">Option 1<br>
</div>
<div class="js-form-item78">
<input type="radio" name="radioQtwo" id="radioQ22">Option 2<br>
</div>
<div class="js-form-item34">
<input type="radio" name="radioQtwo" id="radioQ23">Option 3<br>
</div>
<br>Question 3<br>
<div class="js-form-item111">
<input type="radio" name="radioQthree" id="radioQ31">Option 1<br>
</div>
<div class="js-form-item11">
<input type="radio" name="radioQthree" id="radioQ32">Option 2<br>
</div>
<div class="js-form-item3">
<input type="radio" name="radioQthree" id="radioQ33">Option 3<br>
</div>
<br>Question 3<br>
<div class="js-form-item5">
<input type="radio" name="radioQFOUR" id="radioQ35">Option 1<br>
</div>
<div class="js-form-item-">
<input type="radio" name="radioQFOUR" id="radioQ36">Option 2<br>
</div>
<div class="js-form-itemè">
<input type="radio" name="radioQFOUR" id="radioQ37">Option 3<br>
</div>
<br>
<div id="progress-container">
<div id="progressbar">
</div>
</div>
<div id="percentage">
<p>fff</p>
</div>
SOLVED - Thank you all for your time
I'm having a little trouble getting this one right. Basically I have two radio buttons with different values and I need to add and remove the class "active" from div's that pertain to the value of the radio button. See my code below:
HTML:
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phoneOrWeb">
<input name="phoneOrWeb" id="phoneOrWeb" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="phoneOrWeb">
<input name="phoneOrWeb" id="phoneOrWeb" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<!-- Phone SUB -->
<div class="drawer" id="phone">
<?php include ('formD.php'); ?>
</div>
<!-- /Phone SUB -->
<!-- WEB SUB -->
<div class="drawer" id="web">
<?php include ('formE.php'); ?>
</div>
<!-- /WEB SUB -->
Jquery I attempted:
$("input[name=phoneOrWeb]:radio").click(function () {
if ($('input[name=phoneOrWeb]:checked').val() == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if ($('input[name=phoneOrWeb]:checked').val() == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Your code is very close. First of all, IDs should always be unique. One element per ID on a page. phoneOrWeb is used twice which is not good. Secondly, if you don't want to do a second jQuery selection, you can just grab the value from the target of the event. This code should work as you expected.
$("input[name=phoneOrWeb]:radio").click(function(ev) {
if (ev.currentTarget.value == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if (ev.currentTarget.value == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
.drawer {
width: 100px;
height: 100px;
background-color: green;
margin: 4px;
}
.drawer.active {
border: 3px solid red;
margin: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phoneInput">
<input name="phoneOrWeb" id="phoneInput" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="webInput">
<input name="phoneOrWeb" id="webInput" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<!-- Phone SUB -->
<div class="drawer" id="phone">
Phone!
<!--<?php include ('formD.php'); ?>-->
</div>
<!-- /Phone SUB -->
<!-- WEB SUB -->
<div class="drawer" id="web">
Web!
<!--<?php include ('formE.php'); ?>-->
</div>
<!-- /WEB SUB -->
$("input[name=phoneOrWeb]:radio").change(function () {
if ($(this).val() == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if ($(this).val() == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Use the change event on the input. The below works.
$("input[name=phoneOrWeb]").change(function () {
if (this.value == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if (this.value == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Fiddle: https://jsfiddle.net/04uhjuvc/
PS: ids should be unique, you have the same id in both the radio buttons.
You shoud check this one.
How to use radio on change event?
$(document).ready(function() {
$('input[type=radio][name=bedStatus]').change(function() {
if (this.value == 'allot') {
alert("Allot Thai Gayo Bhai");
}
else if (this.value == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
This depends that the Values of your Radios are equal to the target-element IDs:
$(".radio.toggle").on("click", function() {
$(".drawer").removeClass("active");
$("#"+$(this).val()).addClass("active");
});
You can make use of JQuery toggleClass for this to make it more simple:
$("input[name=phoneOrWeb]:radio").click(function () {
if (this.value == "phone")) {
$('#phone').toggleClass( "active" );
} else if (this.value == "web")) {
$('#web').toggleClass( "active" );
}
});
Try this:
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phone-option">
<input id="phone-option" name="phoneOrWeb" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="web-option">
<input id="web-option" name="phoneOrWeb" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<div class="drawer" id="phone">phone</div>
<div class="drawer" id="web">web</div>
jQuery script:
<script>
$(document).ready(function () {
$('#phone-option').click(function () {
$('#web').removeClass("active");
$('#phone').addClass("active");
});
$('#web-option').click(function () {
$('#phone').removeClass("active");
$('#web').addClass("active");
});
});
</script>
I have an issue that I cant seem to figure out how to fix.. Im still green on javascript.
I am having this markup:
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4"></div>
<div class="area col-sm-4 construction"></div>
<div class="area col-sm-4 available student"></div>
<div class="area col-sm-4 available"></div>
<div class="area col-sm-4 available"></div>
<div class="area col-sm-4 available"></div>
</div>
function areaListing() {
if ($(".area-listing").length) {
var filters = $(".area-listing #list-filter");
var areas = $(".area-listing .area");
areas.show();
var $areas = $('input').on("change", function () {
if (this.id == 'all') {
areas.fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
areas.not($el).hide();
}
$areas.removeClass('filtered');
$(this).addClass('filtered');
})
}
}
And with the javascript I am now filtering fine based on the radio buttons.. However I want to add the possibility to trigger another filter on the "checkbox" to filter out "available" elements. However I can't get it to work.. can anyone assist me? Right now it works on the first checkbox click, but doesnt register when untoggling it.
To clarify: When clicking the checkbox the filtering should remain but only show the areas with available. And when untoggled it should show all.
You can store current filters in variables and change them after clicking on radio or checkbox input.
function areaListing() {
if ($('.area-listing').length) {
var filters = $('.area-listing #list-filter');
var areas = $('.area-listing .area');
areas.show();
var currentFilter = 'all';
var showOnlyAvailable = false;
function filterAreas() {
var currentSelector = '.area';
if (currentFilter !== 'all') {
currentSelector += '.' + currentFilter;
}
if (showOnlyAvailable) {
currentSelector += '.available';
}
var $el = $(currentSelector).fadeIn(450);
areas.not($el).hide();
}
$('input[type="radio"]').on('change', function() {
currentFilter = this.id;
filterAreas();
});
$('input[type="checkbox"]').on('change', function() {
showOnlyAvailable = $(this).is(':checked');
filterAreas();
});
}
}
areaListing();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4">a</div>
<div class="area col-sm-4 construction">b</div>
<div class="area col-sm-4 available student">c</div>
<div class="area col-sm-4 available">d</div>
<div class="area col-sm-4 available">e</div>
<div class="area col-sm-4 available">f</div>
</div>
Here's code for the filtering based on both Checkbox AND Radio button. When any of the radio button or checkbox is checked(or checkbox is unchecked), you need to first get the checked status of checkbox. If this checkbox is checked, only areas with .available should be shown and others should be hidden. If this checkbox is unchecked, there is no need to bother about .available elements.
Here are some suggestions:
Wrap the code interacting with DOM in ready
$('.area-listing').length is not needed as it'll always be true provided that code is executed after page load
filters is never used, thus can be removed.
areas.show() is not needed if .area elements are not hidden.
Instead of ID, use data-filter to get the class on which the filter is to be applied.
Fiddle Demo
// When DOM is completely loaded
$(document).ready(function() {
'use strict';
// Cache element references
var $areas = $('.area');
var $checkbox = $('#available');
var $radios = $('#list-filter :radio');
var checkboxFilter = $checkbox.data('filter');
// Bind change event on radio buttons and checkbox
$('#list-filter').on('change', ':radio, :checkbox', function(e) {
// Get the checked status of checkbox
var isCheckboxChecked = $checkbox.is(':checked');
// Get the checked radio button filter
var radio = $radios.filter(':checked').data('filter');
// Create filter based on checked radio button and checkbox state
var filter = isCheckboxChecked ? '.' + radio + '.' + checkboxFilter : '.' + radio;
if (radio === 'all') {
if (isCheckboxChecked) {
// Show only .available
$areas.filter('.' + checkboxFilter).fadeIn(450);
} else {
// Show all
$areas.fadeIn(450);
}
} else {
// Hide those except filtered
$areas.not(filter).hide();
// Show filtered
$areas.filter(filter).fadeIn(450);
}
}).trigger('change'); // To call the handler on page load
});
label {
margin-right: 2px;
}
div.area {
margin: 5px;
color: green;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4">First</div>
<div class="area col-sm-4 construction">Second</div>
<div class="area col-sm-4 available student">Third</div>
<div class="area col-sm-4 available">Fourth</div>
<div class="area col-sm-4 available">Fifth</div>
<div class="area col-sm-4 available">Sixth</div>
</div>
I think i know what you want to do, first of all, doing the checks from radios or checkboxes is a little bit weird for normal usage, i think you need to use a "filter" button, so i added one to filter every option selected.
This is the JS code:
//Launch the filter with a button
$("#list-filter input[type='button']").click(function(){
//Get the element
var input = $("#list-filter input[type='radio']:checked").attr("data-filter");
var check = $("#list-filter input[type='checkbox']");
//Check for available only
if(check.is(":checked")){
if(input=="all"){ //Show all available
$(".area-listing .area").css("display","none");
$(".area-listing .area.available").css("display","block");
}
else{ //Show only available in the desired area
$(".area-listing .area").css("display","none");
$(".area-listing .area.available."+input).css("display","block");
}
}
else //If not available is checked
{
if(input=="all"){ //Show all
$(".area-listing .area").css("display","block");
}
else{ //Show only the desired area
$(".area-listing .area").css("display","none");
$(".area-listing .area."+input).css("display","block");
}
}
});
This is the full test (i added a CSS to hide all areas by default, and the button to filter all options)
https://jsfiddle.net/psyzc79w/
Tell me if this way is useful for you.
I have a user control in asp.net that outputs markup similar to the following:
<div id="combobox1">
<div id="combobox1_text"><span>combobox 1</span></div>
<div id="combobox1_ddl">
<input type="checkbox" id="combobox1_$1" />
<label for="combobox1_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox1_$2" />
<label for="combobox1_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox1_$3" />
<label for="combobox1_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox1_$4" />
<label for="combobox1_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox1_$5" />
<label for="combobox1_$5">Item 5</label>
<br />
</div>
</div>
A javascript file accompanying this control has the following class (minimal code to reproduce the problem only):
ComboBox = function(cb) {
var pnlContainer = document.getElementById(cb);
var pnlComboBox = document.getElementById(cb + '_text');
var pnlDropdownList = document.getElementById(cb + '_ddl');
var isCollapsed = true;
var collapseDropdown = function() {
if (!isCollapsed) {
isCollapsed = true;
pnlDropdownList.style.display = 'none';
//-- some more custom handling code follows here --
}
};
pnlComboBox.onclick = function() {
isCollapsed = !isCollapsed;
pnlDropdownList.style.display = (isCollapsed) ? 'none' : 'block';
};
pnlContainer.onclick = function(event) {
event.stopPropagation();
};
document.addEventListener('click', function() {
collapseDropdown();
}, false);
}
And finally, on my page I create an instance of the class like this:
cb1 = new ComboBox('combobox1');
All this works fine until there is only one instance of this control. It collapses correctly whenever anything or anywhere outside the control is clicked, just as expected.
The Problem:
The problem happens when there are more than one instances of this control on the page. If one of the comboboxes is open, and user clicks on another instance of my combobox, the previous one doesn't collapse.
JsFiddle for minimal code to reproduce the problem can be found here:
https://jsfiddle.net/x8qjo79f/
I know it is happening because of event.stopPropagation() call, but don't know what to do for this.
Edit the document onclick event listener to capture the event (so it is executed before the bubbling phase) and collapse when its target is outside your combobox.
ComboBox = function(cb) {
var pnlContainer = document.getElementById(cb);
var pnlComboBox = document.getElementById(cb + '_text');
var pnlDropdownList = document.getElementById(cb + '_ddl');
var isCollapsed = true;
var collapseDropdown = function() {
if (!isCollapsed) {
isCollapsed = true;
pnlDropdownList.style.display = 'none';
//-- some more custom handling code follows here --
}
};
pnlComboBox.onclick = function() {
isCollapsed = !isCollapsed;
pnlDropdownList.style.display = (isCollapsed) ? 'none' : 'block';
};
pnlContainer.onclick = function(event) {
event.stopPropagation();
};
// Edit: Capture click event
document.addEventListener('click', function(event) {
if (!pnlContainer.contains(event.target)) collapseDropdown();
}, true);
}
cb1 = new ComboBox('combobox1');
cb2 = new ComboBox('combobox2');
#combobox1,
#combobox2 {
border: 1px solid black;
cursor: default;
width: 200px;
font-family: verdana;
font-size: 10pt;
}
#combobox1_text,
#combobox2_text {
padding: 2px;
}
#combobox1_ddl,
#combobox2_ddl {
border-top: 1px solid black;
display: none;
}
<div id="combobox1">
<div id="combobox1_text"><span>combobox 1</span></div>
<div id="combobox1_ddl">
<input type="checkbox" id="combobox1_$1" />
<label for="combobox1_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox1_$2" />
<label for="combobox1_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox1_$3" />
<label for="combobox1_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox1_$4" />
<label for="combobox1_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox1_$5" />
<label for="combobox1_$5">Item 5</label>
<br />
</div>
</div>
<br />
<input type="text" />
<br />
<input type="button" />
<br />
<input type="checkbox" />
<br />
<span>some random text in the document.. <br />blah. blah.. blah..</span>
<br />
<br />
<br />
<div id="combobox2">
<div id="combobox2_text"><span>combobox 2</span></div>
<div id="combobox2_ddl">
<input type="checkbox" id="combobox2_$1" />
<label for="combobox2_$1">Item 1</label>
<br />
<input type="checkbox" id="combobox2_$2" />
<label for="combobox2_$2">Item 2</label>
<br />
<input type="checkbox" id="combobox2_$3" />
<label for="combobox2_$3">Item 3</label>
<br />
<input type="checkbox" id="combobox2_$4" />
<label for="combobox2_$4">Item 4</label>
<br />
<input type="checkbox" id="combobox2_$5" />
<label for="combobox2_$5">Item 5</label>
<br />
</div>
</div>
You could allow the event propagation in pnlContainer.onclick but remember that the ComboBox was clicked. Inside the document click event handler, you would test if the ComboBox is the clicked one, and allow to collapse only if it is not.
The changes to the Javascript code could look like this:
ComboBox = function(cb) {
var isClicked = false;
...
pnlContainer.onclick = function(event) {
isClicked = true;
};
document.addEventListener('click', function() {
if (isClicked) {
isClicked = false;
}
else {
collapseDropdown();
}
}, false);
}
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().