Wp google maps pro checkboxes to behave like radio button - javascript

I'm having this problem with WP Google Maps Pro filters/categories. Basically the plugin offers to display the categories as select dropdown and checkboxes. And since the select dropdown proved not that much of an help I tried to implement the radio button functionality on the checkboxes.
So what I'm trying to do here is make these checkboxes behave like radio buttons. So when one is checked others become unchecked. There's a catch though. I have to make the click on the parent rather than on the child. The checkbox itself was requested by my client to be hid, since it breaks his design, and I have to make the functionality of the tab switching in order to filter the markers.
I've hidden the checkboxes with css, and I've styled the parent and added some icons with jquery. Below is the html layout.
<div class="parent">
<i class="category-icon-one"></i>
<input type="checkbox" class="wpgmza_checkbox" id="wpgmza_cat_checkbox_4"
name="wpgmza_cat_checkbox" mid="1" value="4" tabindex="0">
First Category
</div>
<div class="parent">
<i class="category-icon-two"></i>
<input type="checkbox" class="wpgmza_checkbox" id="wpgmza_cat_checkbox_4"
name="wpgmza_cat_checkbox" mid="1" value="4" tabindex="0">
Second Category
</div>
Here is the jQuery that I've managed to do so far:
$('.parent').click(function(){
$('.parent').each(function(){
$(this).find('input:checkbox').prop('checked', false);
});
$(this).find('input:checkbox').prop('checked', true);
});
So far this has not proved fruitful, so I need to find a way to make this radio button like functionality while clicking on the parent of the checkboxes. I would appreciate if some light were to shine on this. Thanks :)
EDIT: The plugin makes the filtering of the markers through this piece of code. This where the checked states are being registered only as clicks, and the clicked value then is being used to filter the markers. Hope this helps to clarify my issue!
jQuery("body").on("click", ".wpgmza_checkbox", function() {
/* do nothing if user has enabled store locator */
var wpgmza_map_id = jQuery(this).attr("mid");
if (jQuery("#addressInput_"+wpgmza_map_id).length > 0) { } else {
var checkedCatValues = jQuery('.wpgmza_checkbox:checked').map(function() {
return this.value;
}).get();
if (checkedCatValues[0] === "0" || typeof checkedCatValues === 'undefined' || checkedCatValues.length < 1) {
InitMap(wpgmza_map_id,'all');
wpgmza_filter_marker_lists(wpgmza_map_id,'all');
} else {
InitMap(wpgmza_map_id,checkedCatValues);
wpgmza_filter_marker_lists(wpgmza_map_id,checkedCatValues);
}
}
});

Nick from WP Google Maps here.
I'm a bit late to the party with this but I'll help where I can.
You can change the code to the following:
jQuery("body").on("click", ".wpgmza_checkbox", function() {
var wpgmza_map_id = jQuery(this).attr("mid");
var orig_element = jQuery(this);
if (jQuery("#addressInput_"+wpgmza_map_id).length > 0) { } else {
// get the value of the current checked checkbox
var checked_value = jQuery(this).attr("value");
if (checked_value === "0" || typeof checked_value === 'undefined' || checked_value.length < 1) {
InitMap(wpgmza_map_id,'all');
wpgmza_filter_marker_lists(wpgmza_map_id,'all');
} else {
InitMap(wpgmza_map_id,checked_value);
wpgmza_filter_marker_lists(wpgmza_map_id,checked_value);
}
// reset all other checkboxes
jQuery("input:checkbox[class^=wpgmza_checkbox]").each(function(i) {
if (jQuery(orig_element).attr('value') !== jQuery(this).val()) { jQuery(this).attr('checked',false); }
});
}
});
I've tested this and it works.

Related

Click outside an element doesn't work

I have this code:
function showAll(el){
var id = el.parentNode.id;
var all= document.getElementById(id).getElementsByClassName('items')[0];
if(all.style.display === 'block'){
all.style.display = 'none';
} else{
all.style.display = 'block';
window.addEventListener('mouseup', function(e){
document.getElementById('test').innerHTML = e.target.className;
if(e.target != all){
all.style.display = 'none';
}
});
}
}
<div id="parent">
<div class="selected" onClick="showAll(this);">
</div>
<div class="items" style="display: none">
</div>
</div>
Basically what i want to achieve is: click on selected to display items which is now hidden after that if i click again on selected or if i click outside of items(a random spot on that page or even on selected) i want to be able to hide items.
The problem is that without the EventListener when i click on selected it works to display items and then if i click again on selected it works to hide items but if i click on a random spot it doesn't work to close items.
But when i add EventListener and i click on selected it works to click a random spot to close items but it doesn't work to click selected again to close items.
Can anybody help me with a full JavaScript explanation, please?
You're going to want to use highly reusable code. I use change() and id_() on my web platform all of the time and it's very direct and simple. In the below example the second parameter will make the class empty (you can also use id_('items').removeAttribute('class') for a cleaner DOM (Document Object Model)).
HTML
<input onclick="change(id_('items','');" type="button" value="Display Items" />
<div clas="hidden" id="items"><p>Items here.</p></div>
CSS
.hidden {display: none;}
JavaScript
function change(id,c)
{
if (id_(id)) {id_(id).className = c; if (id_(id).className=='') {id_(id).removeAttribute('class');}}
else if (id) {id.className = c; if (id.className=='') {id.removeAttribute('class');}}
else {alert('Error: the class id \''+id+'\' was not found or has not yet been imported to the DOM.\n\nNew class intended: '+c);}
}
function id_(id)
{
if (id == '' && window['console']) {console.log('Developer: empty id called from: '+id_.caller.toString().split('function ')[1].split('(')[0]);}
return (document.getElementById(id)) ? document.getElementById(id) : false;
}
This code exists from years of refining the same platform instead of industry standard drama of pointlessly changing things. You are two clicks from finding more highly reusable functions on my platform's JavaScript documentation from the link in my profile.

Show div on checkbox check and hide it when unchecked (even on load because localstorage)

So the page must show a div if a checkbox is checked, and hide it when it is unchecked. But I am using localstorage so it shouldn't hide on load of the page but only when it is unchecked. If it is possible, it should be usable for a lot of checkboxes (37 exactly).
My Code:
HTML:
<div id="mob1-div" class="row hide one">Mobilisern1</div>
<div id="mob2-div" class="row hide-div">Mobilisern2</div>
<div id="mob1" class="targetDiv">Mobiliseren 1<input type="checkbox" class="checkbox chk" value="one" data-ptag="mob1-div" store="checkbox1"/></div>
<div id="mob2" class="targetDiv">Mobiliseren 2<input type="checkbox" class="checkbox" data-ptag="mob2-div" store="checkbox2"/></div>
Javascript:
$(function() {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
});
$(function(){
$(".chk").on('change',function(){
var self=$(this);
var aData= self.attr("value");
$("."+aData).toggleClass('hide')
});
});
The problem with this code is that when you check the box the div shows, but if you reload the page the box is still checked. Although, the div isn't visible anymore.
Your issue seems to be centered around the fact that your second checkbox did not specify a value attribute (which all checkboxes need to have for them to make any sense).
I made a few adjustments to your code to make it more valid and compact (replaced store with data-store, used a ternary operator instead of if/then, combined the two document.ready functions into one, and changed your for loop to a forEach). These changes aren't part of the issue, but they do allow for your code to be more brief, which aids in troubleshooting.
localStorage doesn't work in the Stack Overflow snippets, but a working version can be seen in this Fiddle.

Issue removing duplicate val() in :checked .map function

I could use some insight or a helpful reference on where to look for checking values on selected checkboxes and if there are duplicates, only return one.
I'm working on a software trial wizard using bootstrap wizard. The first tab is a "solutions catalog" where the user can filter through hundreds of solutions. Many solution types are duplicate as they apply to multiple industry types.
Once user makes selections they go to tab 2 and review their selections. I'm able to map :checked and join the values in a custom separator in the next step but can't figure out how to only show one instance of a duplicate value.
For example, user might select two types of "Audits" for a customized solution. However, the provisioning team only wants to know that they want an "Audit" module.
<input type="checkbox" class='selection' value="Audits" name="Audits - Manufacturing">
<input type="checkbox" class='selection' value="Audits" name="Audits - Electrical">
<input type="checkbox" class='selection' value="Audits" name="Audits - Retail">
<input type="checkbox" class='selection' value="Trading" name="Trading - Manufacturing">
<input type="checkbox" class='selection' value="Trading" name="Trading - Retail">
My current code is outputting multiple selections of same value and kinda stuck on how to handle this.
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
onNext: function(tab, navigation, index) {
if (index == 1) {
// Make sure we entered the solutions
if (!$('.selection:checked').val()) {
alert('Please select a solution to try');
$('.selection').focus();
return false;
}
}
// Show selections in next tab
$('#showSelection').html('<li>' + $('.selection:checked').map(function() {
return $(this).val();
}).get().join('</li><li>') + '</li>');
}
});
});
You could use an array to store the values you have already seen. Something like:
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
onNext: function(tab, navigation, index) {
if (index == 1) {
// Make sure we entered the solutions
if (!$('.selection:checked').val()) {
alert('Please select a solution to try');
$('.selection').focus();
return false;
}
}
var selections = [];
// Show selections in next tab
$('.selection:checked').each(function() {
var value = $(this).val()
if ($.inArray(value, selections) < 0){
selections.push(value);
}
})
$('#showSelection').html('<li>' + selections.join('</li><li>') + '</li>');
}
});
});
fiddle: http://jsfiddle.net/2a460tfc/10/

Hiding Drop Down Boxes if Radio Button other than default is Clicked

I swear I'm going to learn more JavaScript...
I have this page (which really an include file in another ASP page, but I copied the correct HTML and made it so it'd load by itself for my testing purposes):
FO Samples
This is how it should show when they first load it. If they choose one of the other radio buttons, it should HIDE the 2 dropdown boxes. Using this code (something I found from someone else's question on here), its working.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
But I can't figure out how to make it show them again if they go back to the "I wanna pick my own!" radio. The value of SAMPGROUP is the ID from the database of that sample category group. So it won't necessarily be in numerical order, it might skip #'s (if we delete a category or something). Basically, it should show the dropdowns if SAMPGROUP = 0 and not if its anything else!
I tried changing my code to this (95 being the value of SAMPGROUP for the "Autumm" option), but it doesn't seem to have made a difference.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
} else if (value == "95") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
Any help would be greatly appreciated!!
Mahalo!
You are not setting the "value" in your onchange event, thus it's never equal to 0. Try changing this:
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns()" checked />
to
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns(0)" checked />
Here is the fiddle.
Good luck.
You may not be passing any value to the parameter "value" on calling the function ChangeDropdowns. Please ensure you pass the value like ChangeDropdowns(0) etc..

Using custom jQuery radio buttons with CakePHP Form Helper

I'm using a custom jQuery plugin to convert radio buttons to actual images, and it works with basic checkboxes, but when using Cake's built-in input form helper, it acts more as a checkbox by not unchecking the already clicked options. Not only that, but it isn't populating $this->data (or sending anything when the form is submitted).
The js looks like this:
//##############################
// jQuery Custom Radio-buttons and Checkbox; basically it's styling/theming for Checkbox and Radiobutton elements in forms
// By Dharmavirsinh Jhala - dharmavir#gmail.com
// Date of Release: 13th March 10
// Version: 0.8
/*
USAGE:
$(document).ready(function(){
$(":radio").behaveLikeCheckbox();
}
*/
$(document).ready(function() {
$("#bananas").dgStyle();
var elmHeight = "15"; // should be specified based on image size
// Extend JQuery Functionality For Custom Radio Button Functionality
jQuery.fn.extend({
dgStyle: function()
{
// Initialize with initial load time control state
$.each($(this), function(){
var elm = $(this).children().get(0);
elmType = $(elm).attr("type");
$(this).data('type',elmType);
$(this).data('checked',$(elm).attr("checked"));
$(this).dgClear();
});
$(this).mouseup(function() {
$(this).dgHandle();
});
},
dgClear: function()
{
if($(this).data("checked") == true)
{
$(this).addClass("checked");
}
else
{
$(this).removeClass("checked");
}
},
dgHandle: function()
{
var elm = $(this).children().get(0);
if($(this).data("checked") == true)
$(elm).dgUncheck(this);
else
$(elm).dgCheck(this);
if($(this).data('type') == 'radio')
{
$.each($("input[name='"+$(elm).attr("name")+"']"),function()
{
if(elm!=this)
$(this).dgUncheck(-1);
});
}
},
dgCheck: function(div)
{
$(this).attr("checked",true);
$(div).data('checked',true).addClass('checked');
},
dgUncheck: function(div)
{
$(this).attr("checked",false);
if(div != -1)
$(div).data('checked',false).css({
backgroundPosition:"center 0"
});
else
$(this).parent().data("checked",false).removeClass("checked");
}
});
The PHP/Html looks like this:
<span id="bananas-cat" class="cat">
<?= $this->Form->radio('bananas',array(),array('legend' => false, 'id' => 'bananas', 'name' => 'category')); ?>
<label for="bananas">Bananas</label>
</span>
While it upon first inspection may look correct, when clicked, nothing gets passed within $this->data and it acts like a checkbox and doesn't unselect the value when I add an additional radio checkbox.
Although the radio functionality does work without CakePHP's html form helper like so:
<span id="animals-cat" class="cat">
<input type="radio" name="category" id="animals" />
<label for="animals">Animals</label>
</span>
If anyone can help me out here, I would be forever indebted. I've been trying to solve this for way too long now that I'm considering just scrapping the whole idea to begin with.
What I would suggest is see and compare the HTML output of example and one being generated by CakPHP, try to make it similar to example so that you can get your custom-radio-buttons working.
But if you can not do that I would highly recommend to override those helpers by some parameters so that you can get the exact HTML as an output and Javascript should work flawlessly.
Let me know if that does not work for you.

Categories

Resources