Multiplying with jquery - javascript

I have this simple script, i want to multiply Var a * Var b then Multiply this by Var C with a set number eg 15.
But it doesn't seem to work?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$('input[name="box2"]').keyup(function() {
var a = $('input[name="box1"]').val();
var b = $(this).val();
var c = $(15).val();
$('input[name="box3"]').val(a * b * c);
});
​
</script>
</head>
<body>
<input name="box1" type="text" /><br />
<input name="box2" type="text" /><br />
<input name="box3" type="text" />
</body>

A few changes to do :
var a = parseInt($('input[name="box1"]').val(), 10);
var b = parseInt($(this).val(), 10);
var c = 15; // really no need to try to build a dom element to get an int
Beware never never use parseInt without specifying the radix (parseInt("09") is 0...).
Another problem in your code is that you try to build your jquery collection before the dom is ready. Use this :
<script>
$(function(){
$('input[name="box2"]').keyup(function() {
var a = $('input[name="box1"]').val();
var b = $(this).val();
var c = $(15).val();
$('input[name="box3"]').val(a * b * c);
});
});
</script>
Note that it's also best practice, especially when using jQuery which makes it easy, to have a script element at the end of the body to keep all the javascript that isn't in separate files.

Change var c = $(15).val(); to var c=15;

You should parse value which is string to int:
var a = parseInt($('input[name="box1"]').val());

Related

AutoNumeric change value

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,')
}

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.

Can't invoke a function with js

Here is my html and js:
function calculateFun()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var c = document.getElementById('c').value;
var d = document.getElementById('d').value;
var e = document.getElementById('e').value;
var f = a*b;
document.getElementById('f').value = f;
var g = (f + (f*(d/100))).toFixed();
document.getElementById('g').value = g;
var h = ((1 -((a*c)/e))*100).toFixed();
document.getElementById('h').value = h;
}
<input type="number" id="a" onkeyup="calculateFun();" />
<input type="number" id="b" onkeyup="calculateFun();" />
<input type="number" id="c" value="100" />
<input type="number" id="d" value="50" />
<input type="number" id="e" onkeyup="calculateFun();" />
<br><br><p>******</p><br><br>
<input type="number" id="f" />
<input type="number" id="g" />
<input type="number" id="h" />
I tried this code in JSFIDDLE:
https://jsfiddle.net/1ex3b1sa/
but it is not working. also in my site, the function isn't invoked.
it is strange because, i can invoke other functions that i did, almost with the same way.
i tried changing to onclick, onkeypress or onkeydown, but can't see any results..
any ideas? maybe i have a typo? or maybe its a chrome problem?
In JSFiddle, you need to set your JavaScript wrap to "No wrap - in <head>" or else you'll get an "Uncaught ReferenceError: calculateFun is not defined" error.
Make sure that the function is here:
<html>
<head>
<script type="text/javascript">
function calculateFun() {
// ...
You could actually keep the function definition in the onLoad wrap and change:
function calculateFun() {
To this:
window.calculateFun = function() {
And it will work because you are adding your function as a static method to the browser's Window.
On the left side of jsfiddle.net is a box with "Frameworks & Extensions".
In the second select box you have to select:
No wrap - in <body>
or
No wrap - in <head>
Then it will work. If you dont do that the function will not be defind and it will run just once (in the OnLoad Event).
please learn jquery, its not that hard and will help you!
your fiddle in functioning jquery: https://jsfiddle.net/1ex3b1sa/3/
input-fields got class='calc'
and js:
$('.calc').keyup(function(){
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var d = $('#d').val();
var e = $('#e').val();
var f = a * b;
$('#f').val(f);
var g = (f + (f*(d/100))).toFixed();
$('#g').val(g);
var h = ((1 -((a*c)/e))*100).toFixed();
$('#h').val(h);
});

Javascript value of input

This is supposed to calculate circumference, however, I am only getting a zero returned. What am I doing wrong?
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
var Pi = 3.14159265;
var dia = document.getElementById("txtdia");
var circumf = dia * Pi;
function DisplayText(){
document.getElementById("txtcircumf").value = circumf;
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" value="Change Text" onclick="DisplayText()"/>
</form>
</body>
</html>
The primary problem you have is that this script will run prior to your dom being ready. As a result, even if you were properly grabbing the diameter's value it still wouldn't work, since document.getElementById("txtdia") wouldn't return anything.
I would just fetch the diameter's value each time.
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
The other option of course is to put this entire script after your html. Ie
</body>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
There are 3 distinct issues which you need to fix for this to work correctly.
txtcircumf and textdia are the name of the elements, not the id, so using document.getElementById will fail.
Fix: Add that as an id onto the elements in question:
<input type="text" name="txtdia" id="txtdia" />
<input type="text" name="txtcircumf" id="txtcircumf" />
The elements are not present when the script first runs. This is the issue described by #AdamRakis and his fix is probably best - always retrieve the value when you need it:
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
A minor point, but when you read the .value of a field you get text, as you are doing a mathematical equation it is common practice to ensure the value you're wouking with is numeric. You can use parseFloat for this:
function DisplayText(){
var dia = parseFloat(document.getElementById("txtdia").value);
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
I made a couple structural changes that improve the overall quality of your code :) (see the arrows for changes)
<html>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" id="derp" value="Change Text" /> //<-- added ID, removed inline JS
</form>
<script type="text/javascript">
document.getElementById("derp").onclick = function() { //<-- use this style instead of inline onclicks!
var index = false;
var text = "This text shifts";
var dia = document.getElementById("txtdia").value; //<-- .value, not the whole element!
var circumf = dia * Math.PI; //<-- Math.PI is an object constant, very handy
document.getElementById("txtcircumf").value = circumf;
//no more standard function!
}
</script>
</body>
</html>

How can I ADD form values using javascript?

this is the code i came up with but all it does is this 1+1=11 i need it to do 1+1=2.
<head>
<script type="text/javascript">
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.form1.quantity.value;
two = document.form1.price.value;
c = one + two
document.form1.total.value = (c);
}
function stopCalc(){
clearInterval(interval);
}
</script>
</head>
<body>
<form name="form1">
Quantity: <input name="quantity" id="quantity" size="10">Price: <input name="price" id="price" size="10"><br>
Total: <input name="total" size="10" readonly=true><br>
<input onclick="startCalc();" onmouseout="stopCalc()" type="button" value="Submit">
</form>
</body>
of course this is a really simple form, but you get the idea
please help me tell what i'm doing wrong here
You need to use parseInt() to convert the string to an integer.
c = parseInt(one, 10) + parseInt(two, 10)
use this
c = parseInt(one,10) + parseInt(two, 10);
You need to convert the price values to numeric.
use parseFloat for price since it can have decimal values.
use parseInt with the radix.
e,g:
function calc(){
one = parseInt(document.form1.quantity.value, 10);
two = parseFloat(document.form1.price.value);
c = one + two
document.form1.total.value = (c);
}
You can use the + to convert a string to a number (integer or float)
c = +one + +two;
You can use this
one = document.form1.quantity.value/1;
two = document.form1.price.value/1;

Categories