Creating Dependent Chechboxradio Buttons - jQuery Mobile - javascript

I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/

I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.

Related

Javascript word count price calculator

Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone

Event listener fails to attach or remove in some contexts

I've created a script that attaches an event listener to a collection of pictures by default. When the elements are clicked, the listener swaps out for another event that changes the image source and pushes the id of the element to an array, and that reverses if you click on the swapped image (the source changes back and the last element in the array is removed). There is a button to "clear" all of the images by setting the default source and resetting the event listener, but it doesn't fire reliably and sometimes fires with a delay, causing only the last element in a series to be collected.
TL;DR: An event fires very unreliably for no discernible reason, and I'd love to know why this is happening and how I should fix it. The JSFiddle and published version are available below.
I've uploaded the current version here, and you can trip the error by selecting multiple tables, pressing "Cancel", and selecting those buttons again. Normally the error starts on the second or third pass.
I've also got a fiddle.
The layout will be a bit wacky on desktops and laptops since it was designed for phone screens, but you'll be able to see the issue and inspect the code so that shouldn't be a problem.
Code blocks:
Unset all the selected tables:
function tableClear() {
//alert(document.getElementsByClassName('eatPlace')[tableResEnum].src);
//numResTables = document.getElementsByClassName('eatPlace').src.length;
tableArrayLength = tableArray.length - 1;
for (tableResEnum = 0; tableResEnum <= tableArrayLength; tableResEnum += 1) {
tableSrces = tableArray[tableResEnum].src;
//alert(tableSrcTapped);
if (tableSrces === tableSrcTapped) {
tableArray[tableResEnum].removeEventListener('click', tableUntap);
tableArray[tableResEnum].addEventListener('click', tableTap);
tableArray[tableResEnum].src = window.location + 'resources/tableBase.svg';
} /*else if () {
}*/
}
resTableArray.splice(0, resTableArray.length);
}
Set/Unset a particular table:
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'resources/tableBase.svg');
resTableArray.shift(this);
};
tableTap = function () {
$(this).unbind('click', tableTap);
$(this).bind('click', tableUntap);
this.setAttribute('src', 'resources/tableTapped.svg');
resTableArray.push($(this).attr('id'));
};
Convert the elements within the 'eatPlace' class to an array:
$('.eatPlace').bind('click', tableTap);
tableList = document.getElementsByClassName('eatPlace');
tableArray = Array.prototype.slice.call(tableList);
Table instantiation:
for (tableEnum = 1; tableEnum <= tableNum; tableEnum += 1) {
tableImg = document.createElement('IMG');
tableImg.setAttribute('src', 'resources/tableBase.svg');
tableImg.setAttribute('id', 'table' + tableEnum);
tableImg.setAttribute('class', 'eatPlace');
tableImg.setAttribute('width', '15%');
tableImg.setAttribute('height', '15%');
$('#tableBox').append(tableImg, tableEnum);
if (tableEnum % 4 === 0) {
$('#tableBox').append("\n");
}
if (tableEnum === tableNum) {
$('#tableBox').append("<div id='subbles' class='ajaxButton'>Next</div>");
$('#tableBox').append("<div id='cazzles' class='ajaxButton'>Cancel</div>");
}
}
First mistake is in tapping and untapping tables.
When you push a Table to your array, your pushing its ID.
resTableArray.push($(this).attr('id'));
It will add id's of elements, depending on the order of user clicking the tables.
While untapping its always removing the first table.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
resTableArray.shift(this);
So, when user clicks tables 1, 2, 3. And unclicks 3, the shift will remove table 1.
Lets fix this by removing untapped table
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'http://imgur.com/a7J8OJ5.png');
var elementID = $(this).attr('id');
var elementIndex = resTableArray.indexOf(elementID);
resTableArray.splice(elementIndex, 1);
};
So you were missing some tables after untapping.
Well lets fix tableClear,
You have a array with tapped tables, but you are searching in main array.
function tableClear() {
tableLen = resTableArray.length;
for (var i = 0; i < tableLen; i++) {
var idString = "#" + resTableArray[i];
var $element = $(idString);
$element.unbind('click', tableUntap);
$element.bind('click', tableTap);
$element.attr("src", 'http://imgur.com/a7J8OJ5.png');
}
resTableArray = [];
}
Im searching only tapped tables, and then just untap them and remove handlers.
fiddle: http://jsfiddle.net/r9ewnxzs/
Your mistake was to wrongly remove at untapping elements.

Populate select dropdown

I want to populate a select dropdown when the user click in the select. I am trying this, but apparently the click handler is only activated when the user click in the options, but in my case i don't have options. Here is a demo
$('select').click(function () {
var currentId = $(this).attr('id');
alert(currentId);
var total = $('.total').text();
for (i = 0; i <= total; i++) {
$('<option>').val(i).text(i).appendTo('#' + currentId);
}
});
Try this :As you are appending options for every click and hence you are not able to see the options. You can use .one() to populate options only for the first click and for second time click it will show you the populated options. Also use this
to append options instead of getting id of select box and use it.
$('select').one("click",function () {
var total = parseInt($('.total').text());
for (i = 0; i <= total; i++) {
$('<option>').val(i).text(i).appendTo(this);//use this to append
}
});
JSFiddle Demo
You can try to populate the select on mouse over, it could save you some time and give you more accessibility. Sometimes adding options on click just prevents the select from opening when it's supposed to, which can lead to frustrating the user...

Disable holding the up and down buttons on a jQueryUI spinner

I'm using jQuery 1.7.1 and jQueryUI 1.9.1.
I have a spinner, and every time it changes, a text field will be created or removed to match the number on the spinner. Holding the button will cause the number to change very rapidly, causing a ton of fields to be created or removed.
Not a huge problem since it's client-side, but I just don't like it. So I want to disable the rapid spinning when the user holds the spinner buttons.
I came up with a solution using a function for incremental, which looks like this:
var incrementalFunction = function(numOfSpins) {
if (numOfSpins == 1) {
return 1;
}
return 0;
};
This worked great at first, but caused another issue. Next to each newly created text box, I made a 'remove' button that would remove the element and decrement the spinner. But when I call the stepDown method, for some reason, this calls my incremental function, with an increasing numOfSpins every time it was called. So it would only decrement once.
Anyone have a more straightforward solution to preventing the user from holding the increment/decrement buttons (or the up/down arrows on the keyboard)?
If you upgrade to jQuery UI 1.10, the problem will go away. See https://github.com/jquery/jquery-ui/commit/0d53fbfd0b7651652601b3b8577225ab753aab44 which causes stepUp() and stepdDown() to behave as you'd expect.
If you use the stop event, instead of targeting each increment, you can detect when a selection has been made. Then, you can compare that number to how many are currently there, and determine what to do - remove or add more. Try this:
var targetArea = $("#target_area");
targetArea.on("click", ".remover", function () {
$(this).closest("div").remove();
$("#input1").spinner("stepDown");
});
$("#input1").spinner({
stop: function (event, ui) {
var $this = $(this);
var num = $this.val();
var newTargets = targetArea.find("div");
var difference = num - newTargets.length;
if (difference < 0) {
newTargets.slice(difference).remove();
} else if (difference > 0) {
for (var i = 0; i < difference; i++) {
var newTarget = $("<div><input type='text' /><span class='remover' title='Remove'>×</span></div>");
targetArea.append(newTarget);
}
}
}
});
DEMO: http://jsfiddle.net/PJpUC/1/

Dynamically changing costs in custom pc builder with checked inputs

First, please take a look at my fiddle.
I'm trying to figure out a clean way of making the price next to each item change when any item is selected (in that group, you can image that there will be graphics cards etc in a different section which also will need the same functionality).
If its positive I need the class to be .positive and vice versa, and if the item is selected (+0) then the price difference wont be displayed.
This will also be used on checkbox's.
Non-working example.
You'll want to compare each selected item with items having the same name. In the .each() loop in CalculatePrice(), pass the checked item to this function:
function CalculateDiffs(item) {
var selectedPrice = +item.data("price");
item.siblings(".item_price").text("");
$(".calculation-item[name='"+item.attr("name")+"']").not(item).each(function(){
var price = +$(this).data("price");
var diff = (price-selectedPrice).toFixed(2);
if (diff >= 0) {
diff = "+"+diff;
}
$(this).siblings(".item_price").toggleClass("negative", diff < 0).text(diff);
});
}
As for checkboxes, the above function will take care of hiding the price when it is checked. To display the prices for unchecked checkboxes:
$(".calculation-item:checkbox:not(:checked)").each(function(){
$(this).siblings(".item_price").text("+"+$(this).data("price"));
});
Or, if you want to display the price of a checked checkbox as negative, use this instead:
$(".calculation-item:checkbox").each(function(){
var diff = (this.checked ? "-" : "+") + $(this).data("price");
$(this).siblings(".item_price").toggleClass("negative",this.checked).text(diff);
});
http://jsfiddle.net/gilly3/HpEJf/8/
Actually it's pretty straight forward, all you'll need to do is calculate the difference between the selected price and the price of all the options in the list. Eg, something like this:
$(".calculation-item").each(function(index) {
var my_cost = base_price + $(this).data("price");
var difference = Math.round(my_cost - base_cost);
});
I've created a working jsFiddle for you here: http://jsfiddle.net/HpEJf/6/. You'll need to implement decimal rounding etc but this should put you on the right track :)
If my understanding is correct, you want to display the cost difference from the previously selected radio button and the currently selected radio button.
To do that you need to keep track of the previously selected button. The only way I know of to do that is to set a variable outside the clickhandler scope to keep track of it and update the element in the clickhandler.
The rest is fairly straightforward. I updated your jsFiddle with an example of how to do it. The relevant code is below:
Adding at top of script:
//global for last checked/selected radio
var lastSelection = $(".calculation-item:checked");
//clear existing price diffs set by markup
$('span.processor_price').text('');
Added another function:
function priceDifference(oldPrice, newPrice) {
var difference = {
'cssClass': '',
'inCost': '0'
};
var fixedDiff = '';
var diff = newPrice - oldPrice;
diff = Math.ceil(Math.abs(diff * 100)) / 100;
fixedDiff = diff.toString();
if (newPrice < oldPrice) {
difference.cssClass = 'negative';
difference.inCost = '-' + fixedDiff;
} else if (newPrice > oldPrice) {
difference.cssClass = 'positive';
difference.inCost = '+' + fixedDiff;
}
/* else {
* must be the same, no reason for this block
* as the default empty string will suffice
* as will the cost difference of 0
}*/
return difference;
}
And changed your click handler to:
$(".calculation-item").click(function() {
var difference = {};
if (lastSelection) {
//get difference
difference = priceDifference($(lastSelection).data("price"), $(this).data("price"));
//change class
$(this).siblings('span.processor_price').addClass(difference.cssClass).text(difference.inCost);
$(lastSelection).siblings('span.processor_price').removeClass('positive').removeClass('negative').text('');
if (lastSelection !== this) {
lastSelection = this;
}
} else {
lastSelection = this;
}
CalculatePrice();
});​

Categories