I have tried and failed trying to get this to work so time to ask the experts.
I've got the following HTML:
<input type="button" value="-" class="minus">
<input type="number" value="20" class="input-text">
<input type="button" value="+" class="plus">
<div class="newprice">
20
</div>
Using javascript (jQuery specific is fine) I need to be able to have it so that when someone clicks the plus button, the number inside the .newprice div gets incremented by 20. Likewise when they hit the minus button the number gets decreased by 20.
Also the same goes for if they use the little up/down arrows on the .input-text field.
Or if they type in a value instead of using any of the buttons, then the number in the .input-text div changes accordingly (if someone typed in 3, the .input-text number would change to 60).
PS: if it's easier the .newprice div can be an text field instead. Whatever works.
[To put this all into context, basically its part of a shopping cart but I am trying to show the user how much they will be paying for the product when they enter a quantity. For example, the product costs $20, and if they want 3 of them they will be able to see straight away (before adding to their cart) that this is going to cost them $60.]
I hope I explained it properly.
Thanks in advance.
You can do this.
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
// update the input's total
$('.input-text').val(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
Edit based on comments
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
To increment the number input by 20, add the attribute step like so. The number in that attribute represents how much the value will be incremented each time the up and down buttons are pressed.
<input type="number" value="20" step="20" class="input-text">
I already add some calculation and html for handle the basic price. See demo in jsfiddle
HTML:
Price per item:<input name="basicPrice" value="20" class="input-text">
<br />
<input type="button" value="-" class="minus">
<input name="quantity" id="quantity" type="number" value="1" class="input-text">
<input type="button" value="+" class="plus">
<br />Money much pay:
<span class="newprice">20</span>
JS by jquery :
function calculate(){
var basicPrice = parseInt($(":input[name='basicPrice']").val());
var quantity = parseInt($(":input[name='quantity']").val());
console.log(quantity);
var total = basicPrice * quantity;
$(".newprice").text(total);
}
function changeQuantity(num){
$(":input[name='quantity']").val( parseInt($(":input[name='quantity']").val())+num);
}
$().ready(function(){
calculate();
$(".minus").click(function(){
changeQuantity(-1);
calculate();
});
$(".plus").click(function(){
changeQuantity(1);
calculate();
});
$(":input[name='quantity']").keyup(function(e){
if (e.keyCode == 38) changeQuantity(1);
if (e.keyCode == 40) changeQuantity(-1);
calculate();
});
$(":input[name='basicPrice']").keyup(function(e){
calculate();
});
var quantity = document.getElementById("quantity");
quantity.addEventListener("input", function(e) {
calculate();
});
});
Let's me know if you need any support.
You can do...
var $counter = $('.counter');
$('button').on('click', function(){
var $button = $(this);
$counter.text(function(i,val){
return +val + ( $button.hasClass('up') ? 1 : - 1 );
});
});
with this HTML...
<div class="counter">10</div>
<button class="down">-</button>
<button class="up">+</button>
For the record, you should definitely be using an input for the counter element.
Here's your pure JS example but I believe to catch anything below IE9 you'll have to attach event listeners as well.
jsFiddle
<form>
<input type="button" id="value-change-dec" value="-">
<input type="text" id="new-price" value="0" disabled>
<input type="button" id="value-change-inc" value="+">
<br>
<input type="number" id="change-price">
</form>
document.getElementById("value-change-dec").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value-20;
document.getElementById('new-price').value = value;
});
document.getElementById("value-change-inc").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value+20;
document.getElementById('new-price').value = value;
});
function changeIt() {
document.getElementById('new-price').value = document.getElementById('change-price').value*20;
}
var changer = document.getElementById('change-price');
changer.addEventListener('keydown', changeIt, false);
changer.addEventListener('keyup', changeIt, false);
changer.addEventListener('click', changeIt, false);
Related
I am trying to create a drop down with numbers from 1 - 10 for example. Once a number is selected, it should change the total amount. However I have not succeeded and not sure what else I should do, please help.
I have got something put together so far.
<div class="checkout">
<input type="number" name="quantity" placeholder="How many would you like to order? (numeric numbers only)" class="quantity price" data-price="49" value="">
<p class="total" style='margin-bottom: 0px;' >Total: <span id="total">R49 per month</span></p>
</div>
<script type='text/javascript'>
$(document).ready(function(){
$(".checkout").on("keyup", ".quantity", function(){
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("R" + price * quantity);
})
})
var foo = document.getElementById('.checkout');
foo.addEventListener('focus', function () {
foo.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
</script>
All I need is to change the type from a number to a drop down.
How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
I trying to make auto price calculation on magento 2.1 product. When i test my code on snippet or jsfiddle it works normally, but when runs on real magento site the result of "mouseup" calculate function will display on next click (or from previous click) but on "keyup" worked fine. Did someone have any answers for this case?
$(document).ready(function(){
$(".control").on("keyup mouseup",function(){
var totale = 0;
$(".quantity-number .qty").each(function () {
var qty = parseFloat($(this).val());
//var price = parseFloat($(".price-wrapper").attr("data-price-amount"));
//var price = parseFloat($(".price").attr("data-price-amount"));
//var price = parseFloat($(".price").text());
var price = parseFloat($('.product-info-main span.price').text().match(/\d+/)[0], 10);
/*
var temp=$(".price").text();
var num = temp.match(/[\d\.]+/g);
if (num != null){
var price = num.toString();
}
*/
totale += qty * price;
totale = qty * price;
});
$(".cal-price").html("฿"+totale.toFixed(2));
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="product-info-main">
<span class="price-wrapper" data-price-amount="10">
<span class="price">
฿10.00
</span>
<div class="control">
<div class="quantity-number">
<input type="number" name="qty" id="qty" maxlength="12" value="1" title="Quantity" class="input-text qty">
</div>
<span class="cal-price"></span>
</div>
https://jsfiddle.net/l2esforu/x6332ay3/
If you are wanting to call the function when the value is changed in the input element, add an event listener for the "input" event on the input element itself.
$("#qty").on("input", function () { ... });
However, if you have several quantity inputs, and they are added dynamically, you will want to use a delegate selector like so:
$(".control").on("input", ".qty", function () {
// do stuff
});
Event Delegation Docs
My problem is SOLVED! thanks
After try using every state may happening on main div.
$(document).on("input keyup change click mouseup",".control",function(){
$(".quantity-number .qty").each(function () {
//do stuff
});
}
I have 2 buttons, one + and one - that increments the quantity of items.
I also have a "Price" of the item and a span that displays the price of the item.
What i need is: When the user clicks the + or - buttons, it increments the quantity of items and the total price.
So far my code looks like this:
HTML:
<input type="number" size="4" class="input-text qty text" title="Cantidad" value="1" name="quantity" min="1" step="1">
<input type="button" class="plus" value="+">
<input type="button" class="minus" value="-">
<span class="price">90.00 €</span>
JS
function inc() {
var price = "price";
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
var a = document.getElementsByName("quantity")[0].value;
if((' ' + elems[i].className + ' ').indexOf(' ' + price + ' ') > -1) {
var valOfItem = parseInt(elems[i].innerHTML);
var x = a * valOfItem;
elems[i].innerHTML = x;
}
}
}
I haven't tried it yet but i guess everything will be working as soon as i add my func() to the onClick event on those buttons, i was hoping to do it with jQuery after the document is done loading but i'm not sure how.
Any ideas?
Why not just use javascript (in head) to disable the buttons until page load?
<script language="text/javascript">
window.addEventListener("plus", function() { document.getElementById('plus').disabled = false; }, false);
window.addEventListener("minus", function() { document.getElementById('minus').disabled = false; }, false);
</script>
Then have the buttons disabled by default.
<input type="button" class="plus" value="+" disabled="disabled">
<input type="button" class="minus" value="-" disabled="disabled">
The downside of this is any non-JS users will be unable to use the site. Then again, that's likely the case already.
You can add click event handlers to .plus and .minus and calculate sum based on input value using .text() and .val():
Fiddle.
$(document).ready(function()
{
var basePrice = parseFloat($(".price").text());
$(".plus").click(function()
{
changeValue(1);
});
$(".minus").click(function()
{
changeValue(-1);
});
function changeValue(sign)
{
$("[name='quantity']").val(parseInt($("[name='quantity']").val()) + sign);
var countValue = $("[name='quantity']").val();
var newValue = (basePrice * countValue).toFixed(2);
$(".price").text(newValue);
}
});
I need to be able to add a percentage to the total price when a radio button is selected. The code currently works, but only adds a value to the radio button. I need that, but also need to take the total calculated price with addOns and + a percentage to it.
Does anyone know how I can change this with Jquery?
Thanks in advance.
Jsfiddle: http://jsfiddle.net/4bitlabs/mGLfk/5/
HTML:
<div class="price">Estimate Price $<label for="amount1" class="total">0</label></div>
<p class="itemdesc1">How many "Linear Feet" of boards do you have?</p>
<input id="amount1" class="amount" data-for="amount1" />
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn" data-for="amount1" />Add Blue + 20%</div>
Jquery:
$(function () {
$('.amount').keypress(function () {
changeAmount($(this));
});
$('.addOn').change(function () {
var $original = $('#' + $(this).data('for'));
changeAmount($original);
});
});
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
$('label[for=' + id + ']').text(amount.toFixed(0))
}
Ok, I would rewrite what I understand from your question, please, correct me if I'm wrong...
You have CHECKBOXES, and you have an input where you may write a number of items you want to purchase. Then, you want to know the final price of the items you purchase, applying some considerations depending on what CHECKBOX are clicked.
Well, that said, I'll start first assuring you always trigger an "adding function" when anything changes (let's say, you change the number of inputs, or you click a checkbox). You almost did it, but you pass a parameter and I think that is not necessary. When you'll trigger anytime the calculation, you'll always have the right result.
Other thing, you need to distinguish between "adding checkbox" (adds a price per item) and "percentage checkbox" (adds a percentage to the price), to know what value you have to add. Just add clases to your checkboxes to distinguish between them. I'll add a fiddle:
Changes:
The clasess in the checkboxes, to know what we want to do with any of them, put attention on the add and percentage clasess:
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn add" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn percentage" data-for="amount1" />Add Blue + 20%</div>
Your function adding must be called anytime you change anything, to allow you know what is changed, and set price to zero when changing the value (optional).
$('.amount').keydown(function () {
$('.price label').text('0');
});
$('.amount').keyup(function () {
changeAmount();
});
$('input:checkbox').change(function () {
changeAmount();
});
And last, depending on the class of checkbox clicked, different calculation:
function changeAmount() {
var $amount = 0;
$amount = parseFloat( $('.amount').val() ) * 20;
if (isNaN($amount)) {
$amount = 0;
}
var $add = 0;
$('.add:checked').each(function () {
$add += parseFloat( $(this).val() );
});
// Calculate percentage of the Base product
if ( $('.percentage').is(":checked") ) {
$amount = $amount * (1 + $('.percentage').val()/100 );
}
var $total = parseFloat( $amount + $add );
$('.price label').text( $total.toFixed(0) )
}
The fiddle: http://jsfiddle.net/mGLfk/11/
Hope it likes you! XD
I think I got it http://jsfiddle.net/mGLfk/10/
First, use keyup instead of keypress. I added two separate class for percent and sum.
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.sum.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
var percentage=100;
$('.percent.radio:checked[data-for="' + id + '"]').each(function () {
percentage += parseFloat($(this).val());
});
amount*=(percentage/100);
$('label[for=' + id + ']').text(amount.toFixed(0))
}