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.
Related
I have an existing document that has pre existing pricing. So on the page I have a bunch of elements for example price here with each one having different pricing of course.
How can I write a jquery/javascript script to take each of those prices and divide them by 24 and then append a p tag that shows that calculation, this should happen on page load.
so far i have this, just testing it on click but it gives me the same answer for each, which is the very first occurrence of the price divided by 24.
for ex if they price is 1600, or 500, or 100000 the answer it gives me is always based on 1600.
$(".button").click(function () {
var value = $('.price').text();
var price = parseFloat(value)/24;
$('.price').append('<p>' + price + '</p>');
});
Can someone help please?
Thank you :)
In the above code, your use of the text() method selects only the first element with the class price.
You need to loop over all the elements with the class price.
$(".button").click(function () {
$('.price').each(function(index, el) {
var price = parseFloat($(el).text())/24;
$(el).append('<p>' + price + '</p>');
});
});
This is because of var value = $('.price').text(); it selects the first price it finds.
You should use a variable in the event handler to get access to the item that was clicked on. Then get the price from that.
Assuming the button has a descendant with a price class :
$(".button").click(function (e) {
var value = $(event.currenttarget).find(".price")
...
}
I think something like the following implementation should work:
document.querySelectorAll('.button').forEach(element => {
const priceElement = element.querySelector('.price');
const price = parseFloat(priceElement.textContent) / 24;
const childElement = document.createElement('p');
childElement.textContent = price;
priceElement.appendChild(childElement);
});
$(".button").click(function () {
$('.price').each(function(p){
$('.price')[p].innerHTML = $('.price')[p].innerHTML/24});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='price button'>240</div>
<div class='price'>480</div>
On this page https://fantasy.premierleague.com/a/squad/transfers there is a dropdown where you can select a player's maximum price. It then filters a table below to only show players with a price equal or less than the selected maximum price. With my Chrome extension I have added two buttons which change the selected option
/**
* Increases the price of the /transfers maximum price filter.
*/
function increasePrice() {
const priceFilter = document.getElementById('ismjs-element-price');
if (priceFilter.selectedIndex === 0) return;
priceFilter.selectedIndex -= 1;
priceFilter.dispatchEvent(new Event('change'));
}
/**
* Decreases the price of the /transfers maximum price filter.
*/
function decreasePrice() {
const priceFilter = document.getElementById('ismjs-element-price');
if (priceFilter.selectedIndex === priceFilter.options.length - 1) return;
priceFilter.selectedIndex += 1;
priceFilter.dispatchEvent(new Event('change'));
}
/**
* Adds the increase and decrease price buttons for filtering players by the their maximum price to
* the /transfers sidebar.
*/
function addPriceButtons() {
const priceDiv = document.getElementById('ismr-price');
if (priceDiv.classList.contains('price-filter')) return;
priceDiv.className += ' price-filter';
const increaseButton = document.createElement('div');
const decreaseButton = document.createElement('div');
increaseButton.className = 'price-change-button grid-center';
increaseButton.textContent = '+';
increaseButton.onclick = increasePrice;
decreaseButton.className = 'price-change-button grid-center';
decreaseButton.textContent = '-';
decreaseButton.onclick = decreasePrice;
priceDiv.insertAdjacentElement('beforeend', increaseButton);
priceDiv.insertAdjacentElement('beforeend', decreaseButton);
}
which seems to work fine, as shown in the GIF below
The problem is that it doesn't actually change the players shown in the table. I thought that by adding
priceFilter.dispatchEvent(new Event('change'));
it would work fine. I've also tried 'click' and 'input', but these events don't do anything either.
I've also inspected the select element in Chrome's to see which event listeners it has, and if I could maybe make sense of it. Unfortunately the code is minified, so I can't really tell what to do.
Am I missing something? Where am I supposed to find out how the table is filtered in the first place and how can I trigger this myself?
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 a screen on my ASP.Net page, which, depending on a selection by the user, they get offered between 1 and 5 text boxes. These boxes allow the user to type in an amount.
When the user enters the screen, based on certain criteria, a certain number of these edit boxes are displayed. They are not hidden... if I want 3 boxes, then only 3 boxes are on the screen.
In javascript, as the user types in an amount, a 'Total' edit box is displayed, summing up the values from each box.
So, as the user types, the value in the total updates with the total calculated for all text boxes:
I use:
onkeyup="calculateTotal()"
on the editbox.
To do that, I use the code below:
function calculateTotal() {
var amt0 = $('.txtAmount0').val();
var amt1 = $('.txtAmount1').val();
var amt2 = $('.txtAmount2').val();
var amt3 = $('.txtAmount3').val();
var amt4 = $('.txtAmount4').val();
var amt = Number(amt0);
if (!isNaN(amt1))
amt += Number(amt1);
if (!isNaN(amt2))
amt += Number(amt2);
if (!isNaN(amt3))
amt += Number(amt3);
if (!isNaN(amt4))
amt += Number(amt4);
$('.txtTotalAmount').text('$' + amt);
}
The first issue is that it seems I am losing some precision in the calculation:
I am not sure why I am getting a strange rounding issue, when all I am doing is summing up.
Additionally, it seems a bit dirty, if I added more boxes, I need to modify the code.
Is there a better way for this code to work?
You can something like this:
var sum = 0;
$("input[class*='txtAmount']").each(function() {
if ($.isNumeric($(this).val()) ) {
sum += Number($(this).val());
}
});
$('.txtTotalAmount').text('$' + sum.toFixed(2));