JavaScript keyup and onload to calculate a field total - javascript

I am calculating two text inputs using JavaScript. It works with keyup. Ie when typing, the balance calculates in realtime. However, I want the total to calculate and display not only on keyup, but onload as well, so for when I load the page, that it calculates the fields already.
This is my current working javascript code for keyup only
<script type="text/javascript">
$(document).on("keyup", function() {
var sum = 0;
$(".totalCal").each(function(){
sum += +$(this).val();
});
$("#total").val(sum);
document.getElementById('grandTotal').innerHTML = sum.toFixed(2);
});
</script>

https://jsfiddle.net/L2s5yoth/
HTML:
<input type="text" value="0" class="totalCal"><br />
<input type="text" value="1" class="totalCal"><br />
<input type="text" value="2" class="totalCal"><br />
<input type="text" value="3" class="totalCal"><br />
<div id="total">0</div>
jQuery:
$(document).ready(calculate);
$(document).on("keyup", calculate);
function calculate() {
var sum = 0;
$(".totalCal").each(function(){
sum += +$(this).val();
});
$("#total").html(sum);
}

I think that something like this would be work
<script type="text/javascript">
$(document).ready(calculate());
$(document).on("keyup", calculate());
function calculate() {
var sum = 0;
$(".totalCal").each(function(){
sum += +$(this).val();
});
$("#total").val(sum);
document.getElementById('grandTotal').innerHTML = sum.toFixed(2);
});
}
</script>

Related

Can't get values of input with js

I have a inputs in loop using thymeleaf, I need when hover each iteration get the value and calculate sum
<tr th:each="person : ${persons}">
<td th:text="${person.first_name}"></td>
<td th:text="${person.last_name}"></td>
<td th:text="${person.phone}"></td>
<td><input id="age" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="sum" id="sum"/>
My js script :
<script type="text/javascript">
$(document).ready(function(){
$("#age").each(function() {
$(this).on('input', function(){
calculateSum();
});
console.log("sum :"+sum);
});
});
function calculateSum() {
var sum = 0;
$("#age").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
My code give me on total only the first value (like it doesnt work on 2nd iteration), i dont know why !!
Ids should be unique on a page; as such, id selectors usually only return the first element with that id. You should use classes instead.
<input class="age" class="form-control" type="text" name="age">
Your selectors should then become:
$(".age").each(function(){
// ...
});

How to dynamically calculate discount html/js

I am trying to display a percentage value from ((discount/product price) * 100) using the HTML widget of WordPress' WPForm plugin. The discount is triggered by a "Get Total" button currently but that stops the WordPress Submit button from functioning. How can I trigger the total to appear once the fields are filled in instead of using the button? Form in use here: http://testelementor.temp513.kinsta.cloud/calculator/
<head>
<title>HTML Calculator</title>
<script type="text/javascript">
function calc() {
var p = document.getElementById("wpforms-1365-field_12").value;
var d = document.getElementById("wpforms-1365-field_13").value;
return (d/p)*100;
}
function GetTotal() {
document.getElementById('answer_value').innerText = calc();
}
</script>
</head>
<form>
<input type="button" style="color:#000;" name="Get Total" value="Get Total" onclick="GetTotal()" />
<div id="answer" style="display:block;"> Percent Discount: <span id="answer_value"></span>% </div>
</form>
</body>
</html>
Try oninput or onchange event listener.
function calc() {
var p = document.getElementById("wpforms-1365-field_12").value;
var d = document.getElementById("wpforms-1365-field_13").value;
return (d/p)*100;
}
function GetTotal() {
document.getElementById('answer_value').innerText = calc();
}
<head>
<title>HTML Calculator</title>
</head>
<form>
<input type="number" id="wpforms-1365-field_12">
<input type="number" id="wpforms-1365-field_13" oninput="GetTotal()">
<input type="button" style="color:#000;" name="Get Total" value="Get Total" />
<div id="answer" style="display:block;"> Percent Discount: <span id="answer_value"></span>% </div>
</form>
</body>
</html>
If you can't add oninput() attribute directly to the input element, you can easily add that via JavaScript.
document.getElementById("wpforms-1365-field_13").oninput = GetTotal();
or you can also use the onchange event listener.
document.getElementById("wpforms-1365-field_13").onchange = GetTotal();
The difference is:
oninput will trigger every time someone inserts a character in the input field, while onchange will only occur when the input field loses focus. So, use whichever applies to your application.
Use onchange eventlistener for both you input fields. For convenience, I have added two input fields and removed the button and set the initial values of input as 0 so that we don't get NaN.
function calc() {
var p = parseInt(document.getElementById("wpforms-1365-field_12").value);
var d = parseInt(document.getElementById("wpforms-1365-field_13").value);
return (d/p)*100;
}
function GetTotal() {
document.getElementById('answer_value').innerText = calc();
}
<form>
p - <input type="text" value="0" id="wpforms-1365-field_12" onchange="GetTotal()">
<br>
d - <input type="text" value="0" id="wpforms-1365-field_13" onchange="GetTotal()">
<div id="answer" style="display:block;"> Percent Discount: <span id="answer_value"></span>% </div>
</form>

How to Detect Change in a Text Input Box in jQuery

I have two text input text box and I want to do the total of whatever no entered by the user. Below is my code:
$(document).ready(function(){
var total = 0;
$(".test").on("input", function(){
// Print entered value in a div box
total += parseInt($(this).val());
$("#result").text( total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
When I input 10 first then it takes 11, then if I enter 100 then it takes 111, I am no getting why this happening. Where I am making an error, guide me?
On your code when you enter the first digit it's been calculated to the total because of your code total += parseInt($(this).val()). for example, if your press first digit as 1 then at that time total is updating as total = total + 1 which equals 1, on the second keypress, for example, take 0, then your input value becomes 10. it is calculating to the current total value as total = total + 10. that's why you are getting 11 as answer
Try like this.
$(document).ready(function(){
$(".test").on("input", function(){
let total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>
The reason it didn't showed you the result you want to, is because the calculation is wrong. You now add the number to the total, every time one input field changes. So if you type 123, it takes 0 + 1 , then 1 + 12, then 13 + 123 so you'll have 136 as result.
I wrote a possible solution for your question. The code is in the fiddle below.
You could add a function where you calculate the total of all input fields (may be more than 2, it's generic).
function calculateTotal(){
var total = 0;
$(".test").each(function( index ) {
var value = $(this).val();
if(value == ""){
return;
}
total += parseInt(value);
});
$("#result").text(total);
}
And on the change of your input fields, you just execute that function.
$(document).ready(function(){
$(".test").on("input", function(){
calculateTotal();
});
});
Your example is in this fiddle: https://jsfiddle.net/xL6hgder/2/
You just update total with that input value that you're trying to change.
For getting the total for both input values you have to take both values and add it with the total.
Try below code-
$(document).ready(function() {
$(".test").on("change", function() {
var total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
// Print entered value in a div box
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
$(document).ready(function () {
$(".test").on('input', function () {
var total = parseInt($("#result").text());
total = parseInt($("#myInput").val()) + parseInt($("#myInput1").val());
$("#result").text(total);
});
});
<p><input type="text" class="test" placeholder="Type something..." id="myInput" /></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1" /></p>
<div id="result"></div>
Use the change event instead of the input event. It will only fire when the value is "commited", instead of every keystroke. See mdn for details.

Button only appears or becomes enabled when user scores a certain figure?

I have a radio button form where a numerical value is attributed to each selection. The score is totaled up at the end of the form. A user needs to score a certain amount in order to submit an application.
I have the submit button disabled in the html. I need it to enable only when the user scores over 60. I have tried a few variations of the code but the button just remains disabled. Can anyone point me in the right direction?
</li>
<p>Total Score:<span id="total">0</span></p>
<input type="submit" name="submit_name" value="OK"
class="submit_class" id="SubmitButton" disabled/>
</form>
</body>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script language="javascript">
$(":radio").on("change", function() {
var total = 0;
$(":radio:checked").each(function() {
total += Number(this.value);
});
$("#total").text(total);
});
//ENABLE SUBMIT BUTTON CODE ACCORDING TO SCORE
function submitOnly() {
var current = $('.total').filter(':checked');
if (current.score >= 60) {
sbmtBtn.disabled = false;
}
};
</script>
</html>
In your jquery, you can make a check every time the score changes like so:
$(":radio").on("change", function() {
var total = 0;
$(":radio:checked").each(function() {
total += Number(this.value);
if (total > 60) {
$("#SubmitButton").prop('disabled', false);
}
});
$("#total").text(total);
});
<p>Total Score:<span id="total">0</span></p>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton" disabled />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

use onblur to multiplicar <g:field> grails

hi i want to multiply the values ​​of my box for a decimal value and display it in other textbox with onblur.
<script type="text/javascript">
$(document).ready(function () {
$("#Agregar") {
var pred = $("#predis").val();
var result = parseFloat(pred) * 0.15;
$("#pagoTotal").val(result);
});
});
</script>
The problem is that the function does nothing
<g:field name="predis" id="predis" type="number" onblur="Agregar()" value="${predisInstance.predis}" required=""/>
<g:field name="pagoTotal" id="pagoTotal" type="number" value="${pagoTotalInstance.pagoTotal}" required=""/>
Actually you don´t have a grails problem. It is a javascript problem. Get the inputs by name.
(function($){
$(document).ready(function(){
$('input[name="predis"]').on('blur', function(){
agregar($(this));
});
});
function agregar(predis){
var predis = $(predis);
var pred = predis.val();
var result = parseFloat(pred) * 0.15;
$('input[name="pagoTotal"]').val(result);
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--The <g:field ...> tags would parse to something similar to the following hmtl -->
<input name="predis" id="predis" type="number" value="0" required=""/>
<input name="pagoTotal" id="pagoTotal" type="number" value="0" required=""/>

Categories

Resources