I want to have an order page which allows the costumer to select an item and its quantity and then calculate the total amount ordered in a div.
Initially here's my code:
For the quantity jquery:
<script>
$(function() {
$(".numbers-row").append('<div class="inc button">+</div><div class="dec button">-</div>');
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + "The Price";
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - "The Price";
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
});
The HTML for the items:
<ul>
<li class="numbers-row">
<label>
<input class="calc" type="checkbox" name="combos[]" id="item2-title" value="The Name"/>
The Thumbnail<p>The Title</p>
<input type="hidden" name="item1-val" value="The Price">
</label>
</li>
<li class="numbers-row">
<label>
<input class="calc" type="checkbox" name="combos[]" id="item2-title" value="The Name"/>
The Thumbnail<p>The Title</p>
<input type="hidden" name="item2-val" value="The Price">
</label>
</li>
<li class="numbers-row">
<label>
<input class="calc" type="checkbox" name="combos[]" id="item2-title" value="The Name"/>
The Thumbnail<p>The Title</p>
<input type="hidden" name="item2-val" value="The Price">
</label>
</li>
</ul>
My jquery for the total:
<script type="text/javascript">
function calcscore(){
var score = 0;
var checked=$(".calc:checked ~ input[type=hidden]").each(function(){
score+=parseInt($(this).val());
});
$('#price').text(score.toFixed(2));
}
$(document).ready(function(){
$(".calc").change(function(){
calcscore()
});
});
</script>
And my HTML where the total price of the items will be shown:
<p>Total: PHP <span id="price">0</span></p>
I cant seem to integrate all of them, any help?
There are actually a lot more items, but for the sake of simplifying we'll stick with 3.
PS I only basic jquery and PHP but I can copy paste to the least. Any input is greatly appreciated. Thanks guys
Related
My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});
try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />
I'm looking to update a textbox value when a checkbox is selected, however when a checkbox is selected I get 'NaN'.
Can anyone see where I've gone wrong?
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
var val = parseInt($(this).next().val());
sum += val;
});
$('#sum').val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" onclick="GeographicFunction()">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" onclick="RegionsFunction()">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" onclick="RingfencingFunction()">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />
Why we are using "next()" and "each" together. Also parsing int and passing 0.01 value will always hydrates to 0. Try removing "next()" and parseFloat instead of parseInt
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum += val;
});
$('#sum').val(sum);
});
});
This is how I'd do it with Vanilla Javascript:
const checkBox = document.querySelector("#checkbox")
const textBox = document.querySelector("#textbox")
checkBox.addEventListener("change", () => {
textBox.value = checkBox.checked ? textBox.value = parseFloat(textBox.value) + parseFloat(checkBox.value) : textBox.value = 0
})
<input type="text" id="textbox" value="0">
<input type="checkbox" id="checkbox" for="textbox" value="0.08">
Edit: Updated it after #mplungjan 's comment and your question.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating-point number.
The toFixed() method formats a number using fixed-point notation.
Learn more about toFixed()
Learn more about parseFloat()
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function(){
sum += parseFloat(this.value);
});
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<input id="sum" type="text" />
It took a while to understand what you meant. You just want to sum all checked checkbox values?
$(() =>
$('input[type=checkbox]').on("click", () =>
$('#sum').val(
$('input[type=checkbox]:checked') // checked boxes
.map((i,fld) => +fld.value).get() // array of values
.reduce((a,b) => a+b) // summed
.toFixed(2) // rounded
)
)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" ">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" ">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" ">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />
I have a html where I can filter based on their data but I don't know how to combine it.
This is my script and the search name is working already but the radio button isActive still not working and need to add on my filter. I don't know how to and it on filter.
$('input[type=text][name=search_name').on('input', function(e) {
e.stopPropagation();
e.preventDefault();
var fullname = $(this).val();
var isActive = $('input[type=radio][name=isActive]').val();
searchStudent(fullname, isActive);
});
$('input[type=radio][name=isActive]').on('change', function(e) {
e.stopPropagation();
e.preventDefault();
var fullname = $('input[type=text][name=search_name').val();
var isActive = $(this).val();
searchStudent(fullname, isActive);
});
function searchStudent(fullname, isActive) {
$("ul li").each(function() {
// I don't know how to add the isActive
if ($(this).data('fullname').search(new RegExp(fullname, "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_name">
<span><input type="radio" checked="" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
</div>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>
so when I choose all = 2, then I will see all people, active = 1 I will see the active, then inActive = 0 to see the inactive people.
I would suggest using a single update function that you call when both the inputs or the textField change.
In this update function, you would query the selected checkbox and the text field.
Other solutions would imply recording the selected values or pre-selecting the relevant elements to avoid querying the DOM each time, but in my opinion, it is not worth it.
$('input[type=text][name=search_name').on('input', updateFilter);
$('input[type=radio][name=isActive]').on('change', updateFilter);
function updateFilter(){
var fullname = $('input[type=text][name=search_name').val();
var isActive = $('input[type=radio][name=isActive]:checked').val();
searchStudent(fullname, +isActive);
}
function searchStudent(fullname, isActive) {
$("ul li").each(function() {
if ($(this).data('fullname').search(new RegExp(fullname, "i")) < 0
|| isActive !== 2 && +$(this).data('isactive') !== isActive) {
$(this).hide();
} else {
$(this).show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_name">
<span><input type="radio" checked="true" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
</div>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>
Change your jQuery selector to exclude the data-isActive attributes you don't want:
$("ul li:not([data-isActive='0'])").each(function () {
...
}
Just add a check in the current if-statement. I did refactor your code a bit, since I was having some issues myself. This was mostly because my IDE was annoying me ...
But the snippet works and I hope it'll help you out.
$("input[name='search_name']").on("input", function() {
var fullname = $(this).val();
var isActive = $("input[type='radio'][name='isActive']:checked").val();
searchStudent(fullname, isActive);
//If input is empty, just trigger the checked radiobutton
if(fullname === "")
$("input[type='radio'][name='isActive']:checked").change();
});
$("input[name='isActive']").change(function() {
var fullname = $("input[name='search_name']").val();
var isActive = $(this).val();
searchStudent(fullname, isActive);
})
function searchStudent(pFullName, pIsActive)
{
$("ul li").each(function() {
var element = $(this);
var isActive = element.attr("data-isActive");
if((element.data("fullname").search(new RegExp(pFullName, "i")) >= 0) && parseInt(isActive) === parseInt(pIsActive))
element.show();
else
element.hide();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_name">
<span><input type="radio" checked="" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>
I have a jquery that multiplies the price to quantity. Now I wanted to multiply the total of that to how many orders a costumer would place. Where would I insert my multiplication code? Here's how i envisioned the equation would be total=(price*quantity)*numberoforders. Here's a jfiddle of what I cant eloquently explain
Here's my code:
HTML
<form>
<ul>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName1" data-price="12" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName2" data-price="6" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName3" data-price="4" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
Quantity of Orders
<input min="0" max="5" type="number" class="totalquant" name="quantity" value="1" />
</label>
</li>
</ul>
</form>
<p>Total</p>
<div id="totalDiv">0</div>
Jquery
$('.quantity, .drink').change(calculateTotal);
function calculateTotal() {
var $form = $(this).closest('form'), total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
$('#totalDiv').text(total)* parseInt($(this).siblings('.totalquant').val() || 0, 10);
}
Appreciate all the help
I've made some changes on your code here https://jsfiddle.net/k91d23p6/3/
Basically, you have to multiply the total by the totalQuant after the forEach.
//query the DOM once, instead of on every change
var $form = $('form'); //on a real app it would be better to have a class or ID
var $totalQuant = $('.totalquant', $form);
var totalDiv = $('#totalDiv');
$('.quantity, .drink, .totalquant', $form).change(calculateTotal);
function calculateTotal() {
var total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
var totalQuant = total * parseInt( $totalQuant.val() || 0, 10);
totalDiv.text(totalQuant);
}
How to multiply the Qty textbox with Price textbox then print the output on Subtotal textbox? And then add the grand total of Subtotal textboxes and print the sum on Total Price textbox with keypress event.
<ul>
<li>
Qty<input type="text" name="item_qty0" id="item_qty0" class="item_qty valid" onkeypress="return calProduct(this);" value="1" autocomplete="off" />
Price<input type="text" name="item_price0" id="item_price0" class="item_price valid" onkeypress="return calProduct(this);" value="0" autocomplete="off" />
Subtotal<input type="text" name="item_subtotal0" id="item_subtotal0" class="item_subtotal" disabled="" />
</li>
<li>
Qty<input type="text" name="item_qty1" id="item_qty1" class="item_qty valid" onkeypress="return calProduct(this);" value="1" autocomplete="off" />
Price<input type="text" name="item_price1" id="item_price1" class="item_price valid" onkeypress="return calProduct(this);" value="0" autocomplete="off" />
Subtotal<input type="text" name="item_subtotal1" id="item_subtotal1" class="item_subtotal" disabled="" />
</li>
</ul>
<hr />
<p style="text-align:right;">
Total Price<input name="total_price" maxlength="15" type="text" id="totalPrice" />
</p>
Demo
Here is The working DEMO http://jsfiddle.net/WLSND/
$("input").keyup(function(){
var total = 0;
$('.item_subtotal').each(function (index, element) {
var subtotal = parseInt($(this).parent().find(".item_qty").val())*parseInt($(this).parent().find(".item_price").val()) ;
$(this).val(subtotal);
total = total + subtotal;
});
$("#totalPrice").val(total);
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var sub1 = parseFloat($('#item_subtotal').val(), 10);
var sub2 = parseFloat($('#item_subtotal2').val(), 10);
$('#totalPrice').val(sub1+sub2);
});
FIDDLE
I also made some changes in the HTML regarding IDs