javascript calculation field comparison algorithm - javascript

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});

Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Adding a score to every input field the user fills in the form and displaying it

Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?

Perform calculation of innerHTML number input

At the moment, I display the amount of characters which are typed into a text box.
I wish to use an alternative display option and show the estimated duration. This means the inputted character amount needs dividing by 15 to give an estimated time (there is roughly 15 characters to 1 second of speech)
How can I add a math calculation to the function below?
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
});
You can add an extra element and use that element to calculate the result of dividing the number of characters from the input with the length method and then dividing by 15. Note I use Math.round() to round the numbers.
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
document.getElementById('duration').innerHTML = Math.round(boxInput.length/15);
});
<form>
<input type="text" id="inputTXT" name="firstname">
<div>
<label>characters: <label id="number">0</label></label>
</div>
<div>
<label>duration: <label id="duration">0</label></label>
</div>
</form>

replace characters in price calculation JS

I'm creating a script for percentage calculation on my e-commerce, but I have a problem.
If i use use characters such as: ", . %" the price value says "NaN".
So I made this:
<input type="text" name="cost" onkeyup="disc()"> <br><br>
<input type="text" name="discount" id="prized" onkeyup="updateInput()">
<input type="text" name="price" value="">
<script>
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc(){
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
</script>
How can I replace the characters when they are inserted on cost value or discount value?
I did some research, and I found an interesting function: .replace
I have no idea how to use it in my script.
Someone can help me reach my goal?
You should have to replace special characters , and & like this
var price = $(".price").val().replace(/,/g, "").replace("%", "")
This replace(/,/g, "") will replace multiple replace of comma ,
Ex. 1,00,000 be 100000
Why not validate your user input prior to calling your function? create a regex to only allow the characters you want. As it is your user can input any character they want in the input box. Probably a good idea to limit that.
I don't know whether this is the requirement, any way replace work like below,
var test = "90.56%";
test = test.replace(/[.%]/g, "");
//test will be "9056"

Javascript: Add or Subtract to running total

I am very new to Javascript, only a few weeks, and am stuck on something I assume to be simple. I have searched for hours, but cant find an example to point me in the right direction. Im basically wanting to create a simple "Running Balance" calculator. One textbox has the input (added by using add button) and the other textbox has the output. The output should change depending on what I put into the input textbox and keep adding to the value in the output textbox.
Here is my code in Javascript:
var accountBalance = 0;
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
total = parseInt(inPrice += accountBalance);
document.getElementById("outBalance").value = total;
}
and the HTML:
<form id="form2" name="form2" method="post" action="">
<p>
Enter an amount:
<input type="text" name="inAmt" id="inAmt" />
</p>
<p>
Display Balance::
<input type="text" name="outBalance" id="outBalance" />
</p>
</form>
<p><input type="button" id="addBal" value="Add the amount to the balance" onclick="addBalance()"/></p>
I have a feeling my total variable in my function is what I am screwing up. Thanks in advance for the help!!
This part doesn’t really make sense:
total = parseInt(inPrice += accountBalance);
It takes accountBalance (0), appends it to inPrice (since inPrice is a string), stores the value back in inPrice, parses the result as an integer, and sets total to that integer. What you seem to need is pretty much the reverse, that is:
Parse inPrice so that it’s a number instead of a string
Add it to accountBalance and store the result in accountBalance
Put the new accountBalance in total (or just use accountBalance in the first place)
Or, in JavaScript:
var accountBalance = 0;
function addBalance() {
var inPrice = parseInt(document.getElementById("inAmt").value, 10);
accountBalance += inPrice;
document.getElementById("outBalance").value = accountBalance;
}
You've confused a few variables - the problem was you were never reading the current balance and you were resetting the total variable every time (aside from mixing ints and strings). Here is a version without the total variable:
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
accountBalance += parseInt(inPrice, 10);
document.getElementById("outBalance").value = accountBalance;
}
See it here: http://jsfiddle.net/fdureo1s/

Categories