Using custom jQuery radio buttons with CakePHP Form Helper - javascript

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.

Related

Wp google maps pro checkboxes to behave like radio button

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.

Multiple conditions on single checkbox

I wanted to have a single checkbox in a form but i need to implement multiple scenarios but not sure if this is possible using a single checkbox or if i need radio buttons . Please advise
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
not sure if this is possible using a single checkbox
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
if the requirements 1/2/3 can be met using a single checkbox .The reason i ask is a single checkbox can hold only one value and if there is a way i can alter the value in Jquery dynamically still satisfying all the requirements.
Yes, it is possible. You can create an object having properties set to selectors :checked, :not(:checked, :hidden), :hidden; with corresponding values set to yes, no, blank. Set variable at change event handler using for..in loop, .is()
var obj = {
":checked": "yes",
":not(:checked, :hidden)": "no",
":hidden": "blank"
};
var curr;
$(":checkbox").change(function() {
for (var prop in obj) {
if ($(this).is(prop)) {
curr = obj[prop]; break;
}
}
// do stuff with `curr`
console.log(curr);
});
// check `:hidden`
$(":checkbox").prop("hidden", true)
.change() // `curr` should log `blank`
.prop("hidden", false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="checkbox" />
I have created one sample onchange function where you can handle mutiple events
codepen URL for reference:
http://codepen.io/nagasai/pen/xOGNYW
<input type="checkbox" id="checkTest" onchange="myFunction()">
<input type="text" id="myText" value="checked">
#myText
{
display:none;
}
function myFunction() {
if (document.getElementById("checkTest").checked) {
document.getElementById("myText").style.display = "block";
} else {
document.getElementById("myText").style.display = "none";
}
}

How to combine multiple FIlters together to filter Task Rows using jQuery?

I have hacked together a basic example Task List Table with HTML and using jQuery. I have attached some on change events to my Filter DropDown Selection Fields
Demo: http://codepen.io/jasondavis/pen/MwOwMX?editors=101
I have a Filter Selection Field for each of these:
Assigned User
Task Status
Milestone
Priority
Tags
Independently they all work to get the job done in filtering out non matching results from my Task List Table.
For each Task Row, I store the value of each filterable option in a Data Attribute like this example Task Row HTML:
<tr id="task-3"
class="task-list-row"
data-task-id="3"
data-assigned-user="Donald"
data-status="Not Started"
data-milestone="Milestone 1"
data-priority="Low"
data-tags="Tag 3">
<td>Task title 3</td>
<td>11/16/2014</td>
<td>02/29/2015</td>
<td>Low</td>
<td>Milestone 1</td>
<td>Donald</td>
<td>Tag 3</td>
</tr>
So the actual Text for the Task row does not matter because the Task row will not show all the properties. WHat matters is the value stored in the Task Row Data Attributes.
A Task row/record with a Miledstone set to Milestone 2 will have a Data Attribute like this data-milestone="Milestone 2"
An example JavaScript/jQuery Filter code:
// Task Milestone Dropdown Filter
$('#milestone-filter').on('change', function() {
var taskMilestone = this.value;
if(taskMilestone === 'None'){
$('.task-list-row').hide().filter(function() {
return $(this).data('milestone') != taskMilestone;
}).show();
}else{
$('.task-list-row').hide().filter(function() {
return $(this).data('milestone') == taskMilestone;
}).show();
}
});
So as I mentioned. I can get each of my "FIlters" to work by thereself, however as soon as I try to apply more than 1 filter at a time, it will not work with this current code.
I would appreciate any help in modifying my code to make a working multi-filter example please?
My current demo is here: http://codepen.io/jasondavis/pen/MwOwMX?editors=101
Update Test 2
After some thought, I am thinking that perhaps I need to store all the current Filter values into variables and then on each change event instead of this:
return $(this).data('milestone') != taskMilestone;
It would instead need to be more like this...
return $(this).data('milestone') != taskMilestone
&& $(this).data('priority') != taskPriority
&& $(this).data('tags') != taskTags
&& .... for all filters;
Does that sound about right?
Nevermind, just tried this with no luck!
You were close in your second test. Here's a working demo:
http://codepen.io/luciopaiva/pen/oXpzGw?editors=101
I refactored your code a little and centralized the logic around updateFilters(), which is called every time any change event occurs. It starts by assuming each row should be shown and then tests against each filter that is different from the default value (be it 'Any', 'None' or undefined).
By the way, if you can change data-user-assigned into data-user, here's a slightly improved code that greatly reduces the number of lines of code:
http://codepen.io/luciopaiva/pen/YXYGYE?editors=101
I'm using call so I can pass the DOM element (referenced through this) to the context of changeFilter().
I also put all filters into an object (filters) so I can access each one by its name, like filters[filterName] and be able to automate things.
It's worth mentioning that filters variable is global and the whole thing should be put inside an IIFE.
But let's continue. You can go even further and remove the boilerplate code for each change event, considering you can rename element #assigned-user-filter to #user-filter:
http://codepen.io/luciopaiva/pen/YXYGaY?editors=101
The Javascript of this final approach:
(function () {
var
filters = {
user: null,
status: null,
milestone: null,
priority: null,
tags: null
};
function updateFilters() {
$('.task-list-row').hide().filter(function () {
var
self = $(this),
result = true; // not guilty until proven guilty
Object.keys(filters).forEach(function (filter) {
if (filters[filter] && (filters[filter] != 'None') && (filters[filter] != 'Any')) {
result = result && filters[filter] === self.data(filter);
}
});
return result;
}).show();
}
function bindDropdownFilters() {
Object.keys(filters).forEach(function (filterName) {
$('#' + filterName + '-filter').on('change', function () {
filters[filterName] = this.value;
updateFilters();
});
});
}
bindDropdownFilters();
})();
Here I used the same logic as in the second approach, using filters names to reference each dropdown. Classic boilerplate!

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

Optimizing code to define variables only once, code only works when the vars are in change function and for the code outside change I redefine?

Pretty sure I know the solution... would write .on('change','load', function(){}
correct? <-- Tested didn't work? so I am up to your solutions :)
Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.
This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.
I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...
<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off
<input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1
<input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2
<span class="switch"></span>// the switch button that changes
</span>
Hope that makes sense and the comments are clear
Here is the jQuery
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.hide()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.show()
}
$('.toggle-bg').change(function () {
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.slideUp()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.slideDown()
}
});
it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..
How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}
I just now thought of that, but I wrote all this so I am going to see what others think...
You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :
$('.toggle-bg').on('change', function () {
var value = $('.toggle-bg input.switch-id-value').val(),
moon1 = $('#' + value + '1').is(':checked'),
slider = $('._moon_staticarea_height'),
toggle = $('.toggle-bg');
toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');
As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.
.on('change','load',
supposed to be
// Remove the comma separator if you want to bind the same handler to
// multiple events.
.on('change load',
And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)
or just trigger the change event.(If there is a single instance of a class)
This will just run the same functionality when the page loads.
var toggle = $('.toggle-bg');
toggle.change(function () {
var value = $('input.switch-id-value', this).val(),
moon1 = $('#' + value + '1').is(':checked'),
moon2 = $('#' + value + '2').is(':checked'),
static_slide = $('._moon_staticarea_height');
if (moon1) {
toggle.css({
'background-color': '#46b692'
});
static_slide.slideUp()
} else if (moon2) {
toggle.css({
'background-color': '#333'
});
static_slide.slideDown()
}
}).change();

Categories

Resources