AutoNumeric change value - javascript

I'm trying to make my value to have thousand separators and such, but I don't understand how to use jquery and how it works.
I want to make my value from 1000 to 1,000
and I tried using AutoNumeric like this but failed
var autonumeric = new AutoNumeric.multiple(".form-control");
This is the form where I want to change the value type:
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label for="total" class="label-control" id="labelsubtotal">Total : </label>
</div>
<div class="col-lg-9">
<input type="text" value="" style="text-align: right;" class="form-control" id="grandTotal" name="grandTotal" disabled>
</div>
</div>
</div>
This is how I import AutoNumeric:
<script src="<?php echo base_url();?>js/autonumeric-next/src/AutoNumeric.js" type="text/javascript"></script>
Basically this is what I want to do :
I want the result format changed into currency format
I succeeded in changing only 1 value, this is what I did:
<script>
$('document').ready(function(){
$(function sum() {
console.log($('.calc'))
var sum = 0.0;
$('.calc').each(function() {
sum += parseInt($(this).text());
});
$("#subTotal").val(sum);
let subTotal = new AutoNumeric("#subTotal");
})();
function calculateSubTotal() {
var subtotal = $("#subTotal").val();
$("#subTotalDiscount").val(subtotal - (Math.round(($("#inputDiscount").val() / 100) * subtotal)));
var subtotal_discount = parseInt($("#subTotalDiscount").val());
$("#subTotalTax").val(Math.round(($("#inputTax").val() / 100) * subtotal_discount));
var subtotal_tax = parseInt($("#subTotalTax").val());
var pph = $("#inputpph").val();
$("#SubTotalpph").val(Math.round(parseInt($("#inputpph").val()*subtotal_discount)));
var subtotal_pph = parseInt($("#SubTotalpph").val());
var grandtotal = subtotal_discount + subtotal_tax + subtotal_pph;
$("#grandTotal").val(grandtotal);
}
})
</script>
I'm lost right now.

Also exists a little bit another way to do it. Do next and look what you'll get(one requirement - you need to give number value only):
JS
$('#grandTotal').on('input',function(){
var number, s_number, f_number;
number = $('#grandTotal').val();
s_number = number.replace(/,/g,'');
f_number = formatNumber(s_number);
console.info(f_number);
$('#grandTotal').val(f_number);
});
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
But, if you want just convert value without changing it dynamically then just add this in your attached *.js:
var number, f_number;
number = $('#grandTotal').val();
f_number = formatNumber(number);
console.info(f_number);
$('#grandTotal').val(f_number);
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

Related

How to make a text appear with a desired innerHTML using javascript/jquery

There is a button and a h2 tag. the h2 tag has its visibilty=hidden.
When the button is clicked, I want to call a function that calculates the cost and changes the innerHTML of h2 accordingly and then changes its visibility=visible.
HTML:
<main class="form-signin">
<form>
<div class="card">
<label for="inputAdult">Enter number of adults</label><input type="number" id="inputAdult" class="form-control" placeholder="No. of adults" required>
<label for="inputChildren">Enter number of children (4-12yo)</label><input type="number" id="inputChildren" class="form-control" placeholder="No. of children" required>
<button type="button" onclick="showCost()" id="btn3">Calculate my cost</button>
<h2 class="changeCost">Your total cost: $0</h2>
</div>
</form>
</main>
JavaScript / jQuery :
$("h2").css("visibility","hidden");
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputchildren").val();
if (((a+c)%3==0)||((a+c)%3==1)) {
var rooms = (a+c)/3;
}
else {
var rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}
function showCost() {
var display = "Your total cost is: $" + calculateCost();
var x = $("h2");
x.value = display;
$("h2").css("visibility","visible");
}
Try x.text(display) instead of setting value. That changes the innerText of the element. If you'd like to set its HTML content, use x.html(display).
The value accessor is used for plain HTMLElement objects, not for jQuery-wrapped objects.
Apart from this, you should never access a tag solely by its tag name. Always give it some kind of class name or ID. You already gave it the changeCost class, so you could do $("h2.changeCost") rather than $("h2").
To avoid getting NaN do the following:
Javascript is case sensitive so replace line
var c = $("#inputchildren").val();
with
var c = $("#inputChildren").val();
I would also consider declaring rooms variable from if and else scope so it is accessible on calculations: see full function bellow:
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputChildren").val();
var rooms = 0;
if (((a+c)%3==0)||((a+c)%3==1)) {
rooms = (a+c)/3;
}
else {
rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}

Issues outputting text via JavaScript

https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.

Is it possible to run a single method with and without parameter in Javascript or jQuery?

I need to calculate the tax of total amount during onchange of quantity or price values.
Here is what I did:
function sum() {
var result1 = document.getElementById('result1').value;
var result2 = document.getElementById('result2').value;
var result3 = document.getElementById('result3').value;
var result4 = document.getElementById('result4').value;
var result5 = document.getElementById('result5').value;
var result6 = document.getElementById('result6').value;
var myResult = Number(result1) + Number(result2) + Number(result3) + Number(result4) + Number(result5) + Number(result6);
tax(myResult);
document.getElementById('sumvalue').value = myResult;
}
Here result1,2,3.. are sub total of items. Total amount is passed to the tax calculation.
function tax(tot) {
var taxval = document.getElementById('tax_val').value;
amt = (tot * taxval)/100 ;
document.getElementById('tax_amt').value = amt;
}
tax_amt is the Tax Amount final value. My requirement is: when I change the tax value, I need to run this same method.
Below element is the tax percentage holder. Whenever I change the value it must be frequently change the tax_total.
<input id="tax_val" type="number" value="15" oninput="tax(this_element_value)" >
In your case, I understand that you want realtime update of tax, when input is changed.
I would do something like this:
<input id="tax_val" type="number" value="15" oninput="onInputChanged(this)" >
function onInputChanged(elem) {
tax(elem.value);
}
First you can assign a class to all the elements variables (result1, result2, result3...) then add a event to this class like this:
$(".result").change(function () {
sum();
});
<div>
<input class="input-class" />
<input class="input-class" />
</div>
<script>
$('.input-class').on('change', function () {
/// here you need find input and there value then you can sum of these value.
});
</script>
check this. I think it helps you.

Javascript can't get values from input

I'm trying to get the values from the inputs in my form with JavaScript. But whenever I hit submit, I either get nothing, 0 or undefined. Mostly undefined. It doesn't seem to get any of the values.
Here's the code
<form id="ecoCalculator">
<div class="form-group">
<label for="k0">Start Kapital</label>
<input type="number" name="k0" class="form-control" id="k0">
</div>
<div class="form-group">
<label for="kn">Slut Kapital</label>
<input type="number" name="kn" class="form-control" id="kn">
</div>
<div class="form-group">
<label for="x">Rente</label>
<input type="number" name="x" class="form-control" id="x">
</div>
<div class="form-group">
<label for="n">Terminer</label>
<input type="number" name="n" class="form-control" id="n">
</div>
<div class="ecoButtons">
<input type="button" value="Udregn" class="btn btn-default" onclick="k0Eco()">
<input type="reset" value="Ryd" class="btn btn-default">
</div>
</form>
<div class="ecoResult">
<p id="ecoResult">Resultat</p>
</div>
</div>
<script type="text/javascript">
// Public Variables
var k0 = document.getElementById('k0').value();
var kn = document.getElementById('kn').value();
var x = document.getElementById('x').value();
var n = document.getElementById('n').value();
// Calculation of Initial Capital
function k0Eco() {
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0;
}
I've looked around at different questions but haven't found a solution to this yet.
I've tried to change the names of the inputs, having the function only display a single value, but still no result.
Thanks
value isn't a function, it's a property. Change
var k0 = document.getElementById('k0').value()
to
var k0 = document.getElementById('k0').value
Your script also runs on page load, so nothing is filled yet. You need to put the whole thing in a submit handler:
document.getElementById('ecoCalculator').addEventListener('submit', function(e) {
e.preventDefault();
// your code here
});
Now remove the inline js from the button and make it type submit:
<input type="submit" value="Udregn" class="btn btn-default" />
And remove the function in your js
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0Value;
Here's a working fiddle
you need to parse the input value in int. for eg.
// Public Variables
var k0 = parseInt(document.getElementById('k0').value);
var kn = parseInt(document.getElementById('kn').value);
var x = parseIntdocument.getElementById('x').value);
var n = parseIntdocument.getElementById('n').value);
Use value instead of value(). It is a property not a function.
Put your variables inside your function. When page loads you variables
are getting the value of the inputs and there is nothing there.
function k0Eco() {
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
var k0Value = kn / (1 + x) ^ n;
document.getElementById("ecoResult").innerHTML = k0Value;
}
Put you javascript code inside <head> tag or at least before the button. When you try to fire onclick() event, your function is not created yet.

Categories