Calculating price from <span> value and <input> value - javascript

Today I try to calculating the price from <span> value and <input> value. And then, put the result in <span>.
I already tried this code. This is my html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
So I want to get price value from <span id="price>, get quantity from <input type="text" id="quantity" name="quantity">, and put the result in <span id="total" class="amount"></span>
This is my script code:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
Note: I am using JQuery for increase / decrease quantity (plus & minus button)
Did I wrote something wrong?
Thanks
UPDATE
This is my increase / decrease javascript code:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>

The 'price' field is a span, which do not have a value property. Instead, you need to read the text() from it. Also note that the 'quantity' field has an id, so you would be better to use that as a selector as it's much faster. Try this:
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('#quantity').val());
var total = price * qty;
$('#total').text(total);
Working example

var price = parseFloat($('#price').text()) || 0; //parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
The .val() method is primarily used to get the values of form elements such as input , select and textarea
FIDDLE DEMO

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.active {
color:red;
}
</style>
<script>
$(document).ready(function () {
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
});
</script>
</head>
<body>
<table>
<tr>
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="Text1" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
</tr>
</table>
</body>
</html>

Related

Javascript for counting the values of text input fields

I am trying to create a hotel booking form with an increment counter which I have already setup. Its got 3 input fields and at the end there is a "group total" text input field. I need to ask if anyone could help me with the JS in order to counter the number of individuals in the total group box for when they incrementally add people in the 3 increment counters?
My code is as follows:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
textbox.value++;
}
function decrease() {
var textBox = document.getElementById("text");
textBox.value--;
}
function increase2() {
var a = 1;
var textbox2 = document.getElementById("text2");
textbox2.value++;
}
function decrease2() {
var textBox2 = document.getElementById("text2");
textBox2.value--;
}
function increase3() {
var a = 1;
var textbox3 = document.getElementById("text3");
textbox3.value++;
}
function decrease3() {
var textBox3 = document.getElementById("text3");
textBox3.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease()">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease2()">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase2()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease3()">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase3()">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="">
</a>
You can simplify your code by adding this to all onclick function calls so we can know which element called the function and with that we can figure out it's parent along with the correct input element to increment. In the end we call the increaseTotal() or decreaseTotal() function to update the group total field.
Note: I'm guessing you don't want to be able to decrease a field beyond 0, so I added that constraint as an if statement in the decrease() function. I also made the totalPersons input field's value to default to 3 because all of the 3 other inputs default to 1.
Run and test:
function increase(el) {
var textbox = el.parentElement.querySelector('input');
textbox.value++;
increaseTotal();
}
function decrease(el) {
var textBox = el.parentElement.querySelector('input');
if(textBox.value > 0) { // <- if value is at least 1
textBox.value--;
decreaseTotal();
}
}
function increaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value++;
}
function decreaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="3">
</a>
You could just increase/decrease the value attribute of the totalpersons element within the increase/decrease methods as well.
For example:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
var totalpersons = document.getElementById("totalPersons");
textbox.value++;
totalpersons.value++;
}
Note that the values of text boxes are always strings in javascript. The parseInt() function will convert them to integers.
https://jsfiddle.net/y473L1bt/2/
function updateTotal() {
var textbox = document.getElementById("text");
var textbox2 = document.getElementById("text2");
var textbox3 = document.getElementById("text3");
var total = document.getElementById("totalPersons");
total.value = parseInt(textbox.value) +
parseInt(textbox2.value) + parseInt(textbox3.value);
}
function increase(id) {
var textbox = document.getElementById(id);
textbox.value++;
updateTotal();
}
function decrease(id) {
var textBox = document.getElementById(id);
var a = textBox.value - 1;
if (a >= 0) {
textBox.value = a;
}
updateTotal();
}

Sum two textbox values and get grade letter in third textbox

I have an HTML form with three textboxes. I want to sum them automatically using jQuery. At the same time, I want to use if–else statements to check if the result in third textbox is greater than 100. The value in the next (forth textbox)should be A.
See the code below :
<form>
<input type="text" class="number">
<input type="text" class="number">
<br>
<input type="text" id="total" disabled />
<input type="text" id="total2" disable />
<!--i want the letter A to appear in forth textbox if the value in third textbox is > 100 ---->
</form>
<script>
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
if ($('#total').val(sum) > 100) {
form.total2.value = "A";
}
});
}
});
</script>
</body>
</html>
$('.number').on('keyup',function(){
var sum = 0;
var grade = 'B';
$('.number').each(function(){
sum += parseInt($(this).val());
});
$('#sum').text(sum);
if(sum>100){
grade = 'A';
}
$('#grade').text(grade);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" class="number" placeholder="number 1">
<input type="textbox" class="number" placeholder="number 2">
<div>
Your total mark is <span id="sum">0</span>.
<br>
Your grade is <span id="grade">F</span>.
</div>
You can use the following solution:
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += parseInt($(this).val());
});
$('#total').val(sum);
if (sum > 100) {
$('#total2').val("A");}
});

Add an input value to a database value

I am working on a project where I have to add a database value to in input value.
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
</div>
In above code 680 will come from the database. Here I want to add an input number to that 680. I am very new to jQuery.
My JavaScript code is
$(document).ready(function() {
var total = 0;
$("input").keyup(function(){
var priceList = $('.price');
$.each(priceList, function(i, price){
total += parseFloat($(price).text());
});
alert(total);
});
});
</script>
In this it outputs "NaN".
In this it outputs "NaN".
You get this message since you're trying to loop through div's and parsing the text of them, when it's empty. You need to loop over input's instead.
You could init the total with the database value then loop through the input's and add the parsed values to total in every iteration.
NOTE: Use input event instead when you track the user input since it's more efficient.
Multiple inputs:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
$('.price input').each(function() {
total += parseFloat($(this).val()) || 0;
});
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Single input:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
total += parseFloat($(this).val()) || 0;
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Here you go
var result = 0;
var price = +$('#price').text();
$('input[type="number"]').on('input', function() {
var val = +$(this).val();
result = parseInt(val + price);
$('#price').text(result)
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price" id="price">680</div>
<div class="price">
<input type="number" name="name">
</div>

How do I use javascript or jquery to find a sum and product of values from a forms field inputs?

How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>

2 name attributes for a field in a form

I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>
HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.

Categories

Resources