I'm looking to create conditions for my ticket system with jQuery. I have my code that I can increase or decrease the basket total depending on the number of tickets but I want to take a step further and have conditions that have to be met to add the tickets with pop ups that tell you there's an issue
For example: you can't have a child ticket without and adult ticket... or you can't have more than 2 carers... etc
I've tried adding additional if statements within my code that adds increments/decrements the ticket totals but I can't get the conditions to work
I tried using a switch statement but I'm really not that experienced with JS to execute that properly but I feel it may be an option?
Here's a simplified snippet of my code:
var totalPrice = 0;
$($(".valueBtn")).on("click", function(e) {
var currTicket = $(this).closest("li");
var targetClass = e.target.className;
var targetTicketType = $(this)
.closest("li")
.attr("data-type");
var targetTicketPrice = $(this)
.closest("li")
.attr("data-price");
//plus value
if (targetClass.indexOf("plus") > 0) {
var currAmount = $(currTicket)
.find(".currentValue")
.html();
if (currAmount >= 0) {
$(currTicket)
.find(".currentValue")
.html(
parseInt(
$(currTicket)
.find(".currentValue")
.html()
) + 1
);
totalPrice = totalPrice + parseFloat(targetTicketPrice);
}
}
//minus value
if (targetClass.indexOf("minus") > 0) {
var currAmount = $(currTicket)
.find(".currentValue")
.html();
if (currAmount > 0) {
$(currTicket)
.find(".currentValue")
.html(
parseInt(
$(currTicket)
.find(".currentValue")
.html()
) - 1
);
totalPrice = totalPrice - parseFloat(targetTicketPrice);
}
}
//update basket total
$("#basket").html(parseFloat(totalPrice).toFixed(2));
});
You can see it here:
https://codepen.io/cheesycoder/pen/KLjWPM
I'm just looking for a nudge in the right direction.
If anyone can help me create conditions that won't allow child tickets to be added without adult tickets maybe I can work out the rest of my conditions from there.
Related
The website is a school, each school day has a set of 4 lessons with each lesson costing £7.50. When the user selects a day they go to a payment page where all 4 lessons are automatically selected as checkboxes, so the total cost is £30. The user can tick or untick each box to add or remove lessons which in turn changes the total amount on screen. The total amount is a html element with an id of #fullamount and a value of £30 :
<h6>Total Cost : <div id="fullamount" name="fullamount">£30</div></h6>
The problem I am having is that if the user proceeds to the external payment page(after selecting all lessons they want) but then decides to click on the back button to return to the original page - the checkboxes remain as they were but the total(#fullamount) returns back to the original state of £30 so if they had only selected 2 checkboxes it should be £15 but it shows up as £30, then if the user checks the other 2 checkboxes the total becomes £45.
Here is the Javascript:
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#fullamount");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("£", "") || 0);
var cur_total = +($total.html().replace("£", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("£" + cur_total);
$total.val(cur_total);
});
$('#myform').submit(function(e) {
e.preventDefault();
var $total = $("#fullamount");
var amount = $('#amount');
var thetotal = +($total.html().replace("£", "") || 0);
amount.val(thetotal);
this.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm finding it quite hard to explain but I hope I made some sort of sense. Looking for a solution and struggling with it a bit. Any kind of help or advice would be really appreciated. Thanks.
I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when click changes the amount to $5. I'm trying to get get it so that when the user changes the amount from 5 that it changes the amt = to user input.
The bit of script that changes it
function setDonrAmount(id){
var amt = id.substring(10);
if( amt == 'Other' ){ amt = 5}
var others = id.substring(0,10);
$("button[id*="+others+"]").removeClass('active');
$('button#'+id).addClass('active');
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
I've made a few updates to setDonrAmount() to handle custom donations.
$("#donrAmountButtons").on("click", function() {
var amt = id.substring(10);
setDonrAmount(amt);
$('#donrAmount' + amt).addClass('active');
});
$("#donrAmountInput").on("focusout", function() {
setDonrAmount($("#donrAmountInput").val());
$('#otherAmount button').addClass('active');
});
function setDonrAmount(val) {
var amt = val || 0;
if (amt.length < 2 && amt < 5)
amt = 5;
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
$('#donrAmountButtons .active').removeClass('active');
}
You'll want to check for a keyup event on the input field, and make the selection when that happens. Something like... (inside document.ready)
$('#donrAmountInput').on('keyup', function() {
// Probably best to strip any non-numeric characters from the field here
amt = $(this).val();
// pseudo-code: $('#donrAmountOther').select(); as I'm not sure about jQuery's handling of input group buttons. There'll be a way to select this one somehow!
});
I have drop down menus, the last 2 are price and tickets which then makes a calculation and shows the total amount on screen when selected. It works fine although if i change the selection to a different price the total does not update. Also the same idea applies to the part where the user selects 4 or more tickets and an message appears on screen. Im sure its something simple but i cant seem to figure it out.
I have attached a Jsfiddle.
http://jsfiddle.net/Dwdqg/
function totalPrice(ticketCount,priceAmount)
{
if (tickets.selectedIndex != 0 && price.selectedIndex != 0) // if the price and tickets is not 0 or not selected
{
tickets.onchange = ticketCount; //when tickets is changed assign the index to var ticketCount
price.onchange = priceAmount;
var ticketCount = tickets.value; //get the value of ticketCount index
var priceAmount = price.value;
var totalPrice = (ticketCount * priceAmount);
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
}
if (ticketCount >= 4) // if ticketCount is 4 or more
{
totalPrice = totalPrice + 10; // add on 10 to the price
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
document.getElementById("moreTickets").innerHTML = ("Buying four or more tickets will add an additional £10 fee.")
}
}
You're not calling totalPrice in your change handlers.
For example:
price.onchange = function()
// totalPrice needs to be called
}
You've attached it here
<select name="tickets" id="tickets" onChange="totalPrice(tickets)" style="width:120px">
However, that only responds to changes to number of tickets. You haven't attached it to the other elements.
Also - your onchange only fires once because you're replacing the option fields using fillList after the change event fires. You can either reattach the handler or have it respond to a click event.
With that said - I don't recommend attaching handlers as HTML attributes and I suggest cleaning up your code to be more readable.
Looking for some help on how to write a function to filter out certain divs with certain classes.
Essentially I have thrown together a quick e-commerce example. There are lists of different filters, with values. There are then products. Each product div has a number of classes applied to it, e.g "green" or "adult" or "wool" - these are the filterable parameters.
Not being savvy at all with JS I'm trying to write something, but looking for some advice. Here is basically what I'm after:
Starts with displaying all
If user selects GREEN, all items that do not have GREEN attributed are display:none'd (with a fade transition
Rep #2 for any attribute checked
Notes: multiple attributes can be checked, when items are unchecked, everything needs to reappear.
Any help? I guess it's basically linking up the value of each checkbox to the class.
Not sure if there is a better way codewise to do this... data attributes maybe?
Working example of the code here (obviously no JS)
Updated your fiddle and added some jQuery to hide the divs where the classes don't match the selected checkboxes.
Demo: fiddle
JS is a bit verbose, you can refactor it further if you like:
$(document).ready(function() {
var allSelectedClasses;
allSelectedClasses = '';
$('input[type="checkbox"]').click(function(){
//ensure the correct classes are added to the running list
if(this.checked){
allSelectedClasses += '.' + $(this).val();
}else{
allSelectedClasses = allSelectedClasses.replace($(this).val(), '');
}
//format the list of classes
allSelectedClasses = allSelectedClasses.replace(' ', '');
allSelectedClasses = allSelectedClasses.replace('..', '.');
var selectedClasses;
var allSelected;
allSelected = '';
//format these for the jquery selector
selectedClasses = allSelectedClasses.split(".");
for(var i=0;i < selectedClasses.length;i++){
var item = selectedClasses[i];
if(item.length > 0){
if(allSelected.length == 0){
allSelected += '.' + item;
}else{
allSelected += ', .' + item;
}
}
}
//show all divs by default
$("div.prodGrid > div").show();
//hide the necessary ones, include the 2 top level divs to prevent them hiding as well
if(allSelected.length > 0){
$("div.prodGrid > div:not(" + allSelected + ")").hide();
}
});
});
I added a new class to your Colors ul. Hope that's okay.
Here's a crude version of a filtering function, it only takes colors into account so you have to modify it yourself to take everything into account but the basic outline is there.
It can be refactored massively! :)
Since you're using jQuery:
$('ul.colorFilter li input[type="checkbox"]').click(function(){
var checkedBoxes = $('ul.colorFilter li input[type="checkbox"]:checked');
var listOfClasses = [];
checkedBoxes.each(function(index, el){
listOfClasses.push(el.value);
});
if(listOfClasses.length >= 1){
$('div.prodGrid').children('div').hide();
for(var i = 0; i < listOfClasses.length; i++){
$('div.prodGrid > div.'+listOfClasses[i]).show();
}
} else {
$('div.prodGrid > div').show();
}
});
I made a fiddle as well:
http://jsfiddle.net/Z9ZVk/4/
I'm trying to write a form builder where users can generate a signup form. I need to limit the amount of items that the user can create however they also need to delete the items.
Originally I had
var limit = 5;
var counter = 0;
if (counter == limit) {
However when the user deleted items the counter remained the same and so they couldnt replace the deleted form element with a new item. So what I want to do is count how many items are currently active. I tried to do this by giving each new element a class (.kid) and then counting the amount of divs with that class but it didnt work.
Could anyone point me in the right direction? This is what I have so far however it doesn't work.
var limit = 6;
var num = $('.kid').length;
function addAllInputs(divName, inputType){
if (num == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
Cheers all!
You need to capture the current counter in a closure. Decrease the counter when the user deletes an item and increase it after an item is created. Your code sample doesn't reveal how you handle the deletion, but I'll try to illustrate what I mean with a small code snippet:
$(document).ready(function () {
var limit = 5;
var counter = $('.kid').length;
$('#triggers_delete').click(function () {
/* delete the item */
counter--;
});
$('#triggers_creation').click(function () {
if (counter == limit) {
alert('Limit reached');
return false;
}
/* somehow determine divName and inputType
and create the element */
addAllInputs(divName, inputType);
counter++;
});
});
function addAllInputs(divName, inputType) {
/* just create the item here */
}
Is there any reason an approach like this won't work? Every time you go to add a new DIV, the length of the current collection is examined to see if it meets or exceeds the limit. Of course, you may need to refine the scope of your selector if there could be other DIVs of the form with the same class ID.
var limit = 6;
function addAllInputs(divName, inputType){
if ( $('.kid').length >= limit ) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
}
Edit: Just a note, I am assuming that you are either removing the deleted items from the DOM or differentiating them from active items with a different class or attribute. Otherwise, the approach I suggested will return a count that includes the deleted items as well.
The only real issue is that your num variable is being defined outside of the function. It will get the number of .kid elements at the time the page loads and will not update. Simply move this line inside the function:
var limit = 6;
function addAllInputs(divName, inputType){
var num = $('.kid').length;
...
Try this
var limit = 6;
function addAllInputs(divName, inputType){
if ($('.kid').length == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = $('div', { 'id': 'child' + (counter + 1), 'class': 'kid' } );
$("inputContainerSelector").append(newdiv);
}