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.
Related
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.
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.
I'm trying to show the total price to the customer by each option that's selected:
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
});
It works, when check or uncheck the check boxes, total price will change. But the problem is if the submitted form has some validation errors on some inputs, the same page loads with given errors & all inputs that user entered before (check boxes too) but total price will not change since I'm using .change method.
As I'm not much familiar with related methods, Is there any method which will calculate total price on page ready and on input change?
You just have to simulate the change event like that :
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
}).trigger('change');
Edit
Since you want when atleast one is selected, use this instead :
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
}).filter(':checked').trigger('change');
.filter(':checked') should return nothing, therefor it will not trigger anything.
what about to recalculate every time the whole bunch of items?
e.g. create the function
function sumup_everything() {
var sum = 0;
$('input[type=checkbox]').each(/* here you calculate */);
/* setup sum value */
}
Then call it on input change and document.ready.
$(function() {
$('input[type=checkbox]').change(function(){ sumup_everything() });
sumup_everything();
});
I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});