Third box locked value JS - javascript

I am using an javascript function script in html to get the product of two input boxes into third.
HTML:-
<input type="text" class="form-control" id="inputBuyPrice" placeholder="0.0" name="price" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyAmount" placeholder="0.0" name="amount" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyTotal" placeholder="0.0" name="total" oninput="calculate()">
And the javascript:-
<script>
function calculate() {
var myBox1 = document.getElementById('inputBuyAmount').value;
var myBox2 = document.getElementById('inputBuyPrice').value;
var result = document.getElementById('inputBuyTotal');
var numb = myBox1 * myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
</script>
Now everything is working fine. But value of total gets locked by product of amount and price. I don't want it to be readonly but input that's value can be changed by user.

In a comment you've said:
Simple thing amount*price to be shown in total, but total can be changed manually and incase again price or amount change , product should be shown in total
If that's what you want, just remove the oninput="calculate()" on inputBuyTotal. That will allow the user to change it however they want, but then changing inputBuyPrice or inputBuyAmount will replace what they changed it to with the product of those fields.
(I wish the shops I buy from let me manually change the total amount to pay... πŸ˜‰)

Change
oninput="calculate()"
to
oninput="calculateAmount()"
and add function calculateAmount()

Related

html output tag doesn't display output

I have initial values displaying in the fields and want the initial total of the calculated value to display.
The total only displays once a field is modified. I am guessing because it reacts to oninput event.
Code:
<form id="form" oninput="result.value = parseInt(field1.value) + parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)">
</output>
</form>
I could type 800 inside the output tag, but I want it to be dynamic.
Your document.write isn't doing anything useful (it's basically saying "set this attribute to the value of this attribute") and can be removed; rather than writing the value into the HTML you can just set the form field's value attribute in js.
Here I've simplified your code by removing the nonessential or nonfunctional parts, moving the javascript out of the HTML attributes, and combining the "initialize" and "update" tasks into a single function:
// these happen implicitly based on the field IDs; I'm redeclaring
// them here just for clarity, but you could leave these next four
// lines out and this code would still work:
var result = document.getElementById('result')
var field1 = document.getElementById('field1');
var field2 = document.getElementById('field2');
var form = document.getElementById('form');
// update value on input:
form.oninput = function() {
// use Number() instead of parseInt() if you want to support non-integer values here
result.value = parseInt(field1.value) + parseInt(field2.value);
}
// set initial value on page load by calling that function:
form.oninput()
<form id="form">
<input type="number" id="field1" value="600">
<input type="number" id="field2" value="200">
Total <output id="result"></output>
</form>
You can use document.getElementById() and specify the id of the input fields.
Because the value for the input fields is a string, you need to convert to those values to type Number by the Number() function.
let value1 = Number(document.getElementById('field1').value);
let value2 = Number(document.getElementById('field2').value);
result.value = value1 + value2;
<form id="form" oninput="result.value=parseInt(field1.value)+parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)"></output>
</form>
You can read more info about document.getElementById() and Number()

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

Calculate 2 sets of input types using javascript in one html page

I have 2 set of input types of text boxes. 2 fields on each. I am trying to calculate and compare each set individually in single page.
The input types have different ids.
<input type="text" id="tmcp_textfield_1" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_2" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3" name="a3" placeholder="a3" value="0">
<br>second set below<br>
<input type="text" id="tmcp_textfield_3" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_4" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3`" name="a3" placeholder="a3" value="0">
My javascript in header:
For First set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_1').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_2').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 6) {
$('#tmcp_textfield_2').val('');
$('#tmcp_textfield_1').val('');
alert('Combination must be below 6');
}
}
</script>
For Second Set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_3').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_4').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 12){
$('#tmcp_textfield_4').val('');
$('#tmcp_textfield_3').val('');
alert('Combination must be below 12');
}
}
</script>
The problem only the first set of calculation work. When i remove the first set of javascript then the second set only work and vise versa.
How could i differentiate the sets in javascript so that both the set of inputs work together in one single html page.
Problem:
You are having same name functions "calculate()" for both sets that's why only 1 is working at a time.
Solution:
Rename the function name to different names like calculateOne() and calculateTwo() then both will work.
Hope this helps

calculating the sum of the array form with javascript

I want to display the number of values ​​in array form. I have a lot of form with only one name is "price []" and have each value on the form. I want to calculate the total value of the form "price []". I'm still a beginner in javascript. and I want to calculate it by using javascript. The following coding that I have made.
<html>
<body>
<form id="hitung" name="hitung">
price 1 <input type="text" name="price[]" class="price" value="1000"/><br>
price 2 <input type="text" name="price[]" class="price" value="3000"/><br>
price 3 <input type="text" name="price[]" class="price" value="2000"/><br>
price 4 <input type="text" name="price[]" class="price" value="1000"/><br>
price 5 <input type="text" name="price[]" class="price" value="3000"/><br><br>
total <input type="text" name="total" class="total"/>
</form>
</body>
</html>
and I want to ask you again, if there is a new input from the outside, then the total will also be changed directly. how to do it. help me please. thank you
Here's an example: http://jsfiddle.net/c4UyA/1/
var sum = 0;
$("form > input[name='price[]']").each(function() {
$this = $(this);
sum += parseInt($this.attr("value"));
});
$("form > input[name='total']").attr("value", sum);

Subtract an integer from a calculated total

I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.

Categories

Resources