Count inputs number onchange - javascript

i have a little problem with my code, i need to count inputs when change the value, my code is working but when i used the increase button the count dont change the value.
HTML CODE:
<div class="input-group input-number-group">
<div class="input-group-button">
<span class="input-number-decrement">-</span>
</div>
<input class="input-number" type="number" value="1" min="0" max="1000" onchange="count(this.value);">
<div class="input-group-button">
<span class="input-number-increment">+</span>
</div>
</div>
<div class="input-group input-number-group">
<input class="input-number" type="text" id="totalcount" placeholder="0" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
JS CODE:
$('.input-number-increment').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val + 1);
});
$('.input-number-decrement').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val - 1);
})
/* Count. */
function count(value) {
var Total = 0;
value = parseInt(value); // Convertir a numero entero (número).
Total = document.getElementById('totalcount').value;
// Valida y pone en cero "0".
Total = (Total == null || Total == undefined || Total == "") ? 0 : Total;
/* Variable genrando la suma. */
Total = (parseInt(Total) + parseInt(value));
// Escribir el resultado en una etiqueta "span".
document.getElementById('totalcount').value = Total;
}
Here is the fiddle
I need to count when i press the + or rest when i press - button, any idea?
Thank so much.

the onchange event listener is triggered when the user changes the input by typing. Therefore .val() wont cause it to fire up.
You can easily trigger the onchange event manually by adding
$(".input-number").change();
to the desired functions in your code.
In your specific case this should do the trick:
$('.input-number-increment').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val + 1);
$(".input-number").change();
});
$('.input-number-decrement').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$(".input-number").change();
})
Now your count function will execute when the user clicks the increment and decrement buttons.

Related

Prevent inserting value greater than max at the same time restrict to decimal

I want to restrict the user input to two decimal places only at the same time restrict user input not greater than the maxvalue. My code below doesn't work together.
JS Code
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
var input = document.getElementById("amt");
// Add event listener
input.addEventListener("input", function(e){
var max = parseFloat(input.max);
this.setCustomValidity("");
console.log(this.value)
if(parseFloat(this.value) > max){
this.value = max;
} else if(this.validity.rangeUnderflow){
this.setCustomValidity("Does not reach the amount requirement");
}
});
html code
<input type="number" min="100" max="999.99" step=".01" name="amt" id="amt" oninput="validate(this)" required>

How do i Multiply the Value of a readonly input field and display the result in another field

I have Three input fields, When you input BTC amount in the first field, it gives you the BTC equivalent in USD. Then i added a hidden input field which holds a specific value, let's say "460", Now i want the BTC equivalent in USD to Multiply the "460" and give the result in a readonly input field. Below the code demonstrating my explanation.
$(".form-control").keyup(function() { //input[name='calc']
let convFrom;
if ($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function(data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if (convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
});
});
<script src="https://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form>
<input type="number" name="btc" class="form-control" id="validationTooltip02" placeholder="BTC">
<input type="number" name="usd" class="form-control" id="a" onkeyup="add()" placeholder="USD" readonly>
The for the multiplication, i added onkeyup function to the USD field,
<script type="text/javascript">
function add() {
var x = parseInt(document.getElementById("a").value);
var y = parseInt(document.getElementById("b").value)
document.getElementById("c").value = x * y;
}
</script>
then tried to collect the result by ID into a field using <input name="amount" class="form-control" type="text" placeholder="0.00000" id="c" aria-label="0.00000" readonly>
This works if i remove readonly in the USD field and type directly but does not work with the result of the BTC to USD sum in the field when it's readonly. I hope i was able to explain this. Please help as i am not an expert.
You are mixing up jQuery and JS together ideally stick with one to avoid confusions. You do not need a separate function add the third input value multiplied by the second value.
You can do all that in your API call function. In addition to get the decimals you need to use toFixed() on the final third input amount as well.
Moreover, i would suggest for better user experience use .on function with input which is better then key-up since you have input type number. You can use increment your number by the click on increase in your input and the new values and total will be reflected instantly instead of use clicking or typing again.
Live Working Demo:
$("#validationTooltip02").on('input', function() { //input[name='calc']
let convFrom;
if ($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function(data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if (convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
//Add here
var a = parseFloat($('#a').val())
var b = parseFloat($('#b').val())
var final = a * b//final amount multiplied by 465
$('#c').val(final.toFixed(2))
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form>
<input type="number" name="btc" class="form-control" id="validationTooltip02" placeholder="BTC">
<input type="number" name="usd" class="form-control" id="a" placeholder="USD" readonly>
<input type="hidden" id="b" value="465">
<input name="amount" class="form-control" type="text" placeholder="0.00000" id="c" aria-label="0.00000" readonly>
</form>
So, I think you should use your add function in the function you already call on .form-control keyup, like this:
$(".form-control").keyup(function() { //input[name='calc']
let convFrom;
if ($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function(data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if (convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
// Here goes the content of the add function
var x = parseInt(document.getElementById("a").value);
var y = parseInt(document.getElementById("b").value)
document.getElementById("c").value = x * y;
});
});

adding the sum of two separate functions

(ETA: I'm working on this for a class and the teacher wants everything to be "oninput"...yes, it's annoying :p )
I'm working on a form where each function miltiplies a number and gives me a "subtotal" on input. I'd like to take the two "subtotal" answers from the two functions and add them togething into a "total" amount. I feel like this should be simple but nothing I've tried works.
Here's what I've got in the javascript that works to give me the two subtotals:
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
document.getElementById('subTotalOne').innerHTML = '$ ' + qty1 * 19.99;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
document.getElementById('subTotalTwo').innerHTML = '$ ' + qty2 * 37.99;
}
Here's the important parts of the html:
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()"/><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()"/><br>
</div>
<div class="price">
<label for="price">Price</label>
<p>$19.99</p>
<p>$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
I'm trying to add the subTotalOne and subTotalTwo and have them output at orderTotal, essentially. :)
Thanks!
//Global variables (concidering ID is unique)
let subTotalOne, subTotalTwo, qty1, qty2, orderTotal;
const setup = () => {
subTotalOne = document.getElementById('subTotalOne');
subTotalTwo = document.getElementById('subTotalTwo');
qty1 = document.getElementById('qty1');
qty2 = document.getElementById('qty2');
orderTotal = document.getElementById('orderTotal');
myCalculator();
myCalculatorTwo();
};
const updateTotal = (target, value) => {
if(target == null || value == null || Number.isNaN(value)) return;
target.textContent = `$ ${value.toFixed(2)}`;
target.setAttribute('data-value', value.toFixed(2));
}
const getTotal = () => {
if(subTotalOne == null || subTotalTwo == null) return 0;
const [value1, value2] = [
Number.parseFloat((subTotalOne.dataset?.value ?? 0), 10),
Number.parseFloat((subTotalTwo.dataset?.value ?? 0), 10)
];
if(Number.isNaN(value1) || Number.isNaN(value2)) return;
else return value1 + value2;
};
const updateOrderTotal = () => updateTotal(orderTotal, getTotal());
const myCalculator = () => {
const value = Number.parseFloat(qty1.value || 0, 10) * 19.99;
updateTotal(subTotalOne, value);
updateOrderTotal();
}
const myCalculatorTwo = () => {
const value = Number.parseFloat(qty2.value || 0, 10) * 37.99;
updateTotal(subTotalTwo, value);
updateOrderTotal();
}
window.addEventListener('load', setup);
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()" min="0"><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()" min="0"><br>
</div>
<div class="price">
<label for="price">Price</label>
<p data-value="19.99">$19.99</p>
<p data-value="37.99">$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
Here's how you do it:
function orderTotal() {
const qty1 = document.getElementById('qty1').value;
const qty2 = document.getElementById('qty2').value;
const total = parseInt(qty1) + parseInt(qty2);
document.getElementById('orderTotal').innerHTML = '$ ' + total;
}
Remove the oninput="orderTotal()" in your span element and trigger the above function using a button click e.g. <button onClick="orderTotal()">Calculate Total</button> or maybe when either of your two inputs' value changes. Also consider using const and let instead of var.
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
Instead of querying the DOM in Ray's answer--as DOM queries should generally be avoided since they are slow W3 Wiki, you could also consider using a shared variable between the two functions.
Also, consider using something else in place of innerHTML, mostly because of efficiency why-is-element-innerhtml-bad-code.
var total1;
var total2;
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
total1 = qty1 * 19.99
document.getElementById('subTotalOne').textContent = '$ ' + total1;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
total2 = qty2 * 37.99;
document.getElementById('subTotalTwo').textContent = '$ ' + total2;
}
function orderTotal() {
document.getElementById('orderTotal').innerHTML = '$ ' + (total1 + total2);
//parentheses because '$' isn't a number so the numbers total1 and total2 will be treated like strings and joined together
}

start a function if another function is active and activate some checkboxes only - JQuery

i Have a function that I want to start only if another function is previously activated.
I have some CheckBoxes and I need to sum its values to get the total.
Only When a user has selected some of the CheckBoxes it must activate another checkbox with a discount.
I want that the discount checkbox get activated after the first selection because, if I don't do so, I could have a negative price.
Then (if it's possible) I want that the discount checkbox get deactivated is a user deselect all the previous CheckBoxes.
Is this possible?
Here's my script. I'm super new in JavaScript/jQuery so this might be a stupid question.
Thank you
$(document).on('change', getCheck);
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
//console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
//console.log(total);
//console.log(price_tot);
$('#rata').text(total +" €");
var finalprice = total;
//var Check = getCheck();
if(typeof(total) != "undefined" && total !== 0) {
$('[type="checkbox"]:checked').not(".sum").each(function(i, el) {
var Discount = parseFloat($(this).val());
finalprice = finalprice - Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
});
};
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="sum" type="checkbox" name="vehicle1" value="1000"> I have a bike<br>
<input class="sum" type="checkbox" name="vehicle2" value="2000"> I have a car<br>
<br><br><br>
<input id="discount" type="checkbox" name="discount" value="200"> Discount<br>
<div id="rata">rata</div>
Replace your js code with this code. the error will be resolved.
$( document ).ready(function() {
$("input[type='checkbox']").on('change', getCheck);
});
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
console.log(total);
//console.log(price_tot);
$('#rata').html(total +" €");
var finalprice = total;
var Check = function getCheck(){
if(typeof(Check) != "undefined" && Check !== null) {
$("#discount").toggle();
var Discount = parseFloat($(this).val());
finalprice -= Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
};
};
});
};

How do I add a #.## value to a textbox that already has another ##.## value in it only if a checkbox is checked?

I have been trying to figure out how to make it so that if a specific checkbox is checked, the total amount in a textbox gets 50.00 added to it when the submit button is clicked, before it submits the form. In fact, it would be better to have the update happen as soon as the checkbox is checked.
Here's what i tried so far:
<!DOCTYPE html>
<html>
<head>
<script>
function toggle(){
var indoorCamping = 50.00;
var total = 0.00;
if(document.getElementByName('fifty').is(':checked')){
total = (indoorCamping + document.getElementsByName('Amount').value);
document.getElementsByName('Amount').value = total;
}
else{
return;
}
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<input type="checkbox" name="fifty" value="indoor"/>
<label for="Amount">Amount <span class="req">*</span> <span
id="constraint-300-label"></span></label><br />
<input type="text" class="cat_textbox" id="Amount" name="Amount" />
<p id="demo"></p>
<button onclick="toggle()">Click me</button>
</body>
</html>
The value of a text-input is always text (a string) initially. This value needs to be explicitly converted to a number before adding to it, otherwise it concatenates the text. So "20" would become "5020".
Borrowing mohkhan's code:
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value * 1);
document.getElementById('Amount').value = total;
}
}
</script>
I've multipled by 1 which is one way to convert "20" to a number. Number(x), parseInt(x) and parseFloat(x) are other ways.
I would prefer to use an object variable though, amt:
<script>
function toggle(checkbox) {
var indoorCamping = 50.00;
var total = 0.00;
var amt = null;
if (checkbox.checked) {
amt = document.getElementById('Amount');
total = (indoorCamping + amt.value * 1);
amt.value = total;
}
}
</script>
Add the click event on the checkbox then. Like this...
<input type="checkbox" name="fifty" value="indoor" onclick="toggle(this);"/>
And then in your script...
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value);
document.getElementById('Amount').value = total;
}
}
</script>

Categories

Resources