calculate division of fields dynamically using Jquery or Javascript - javascript

I'm "trying" to figure out how to calculate a division between to fields dynamically to display in another field, the thing is, all examples I've seen are sums, and those used something like this: $('#field').each(function(){....});.
I can't do that because there's no way of know which is the dividend and which is the divisor. I tried using "bind", to try to attach the function to the field. It didn't work.
Also tried putting "onChange="CalcularSaldo()" on the input field; no luck, but mainly because i'm pretty sure my function is wrong:
<script type="text/javascript">
$(document).ready(function() {
function calcularSaldo() {
var costo = document.getElementById("costo_ad").value;
var vida = document.getElementById("vida_util").value;
document.getElementById("saldo_dep").value = costo / vida;
}
});</script>
Inputs:
<label for="costo_ad">Costo de Adquisicion</label>
<input name="costo_ad" type="text" id="costo_ad" class="round default-width-input" />
<label for="vida_util">Vida Util</label>
<input name="vida_util" type="text" id="vida_util" class="round default-width-input" />
<label for="saldo_dep">Saldo a Depreciar</label>
<input name="saldo_dep" type="text" id="saldo_dep" class="round default-width-input" disabled />
and the function should be something like this:
saldo_dep = costo_ad / vida_util

suppose we have the following fields
<input type="number" id="field1">
<input type="number" id="field2">
<span id="label"></span>
so, you'd want to attach the jquery function to some action on the fields, like after the user finishes entering text in either of the boxes
$("#field1, #field2").keyup( function(){
var n1 = $("#field1").val();
var n2 = $("#field2").val();
var result = n2/n1;
$("#label").text(result);
});
Example is in jsFiddle... http://jsfiddle.net/A3qat/5/

Related

How to print the values in the same input text field using JS

I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box. The first 4 fields are my inputs and the last text field is my output. unable to debug the issue. kindly find the code and help to find the issue.
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(h+w+g+t);
document.getElementById('result').innerHTML=total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2"id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<!--
<p
id="result">
</p>
-->
<button id="btn" onClick="JS()">Calculate</button>
There are two keys to resolving your issue:
Coerce your inputs to numbers, which I'm doing by adding a + in front of the value assignments. If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.
Set the value of the input element, not the innerHTML. If you'd rather use a <p> element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText.
See example here:
function JS() {
var h = +document.getElementById('h').value;
var w = +document.getElementById('w').value;
var g = +document.getElementById('g').value;
var t = +document.getElementById('t').value;
let p_result = document.getElementById('p_result');
var total = (h + w + g + t);
document.getElementById('result').value = total;
p_result.innerText = total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2" id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<br>
<p id="p_result" style="color:red;"></p>
<br>
<button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value instead of .innerHTML
also, you should convert inputs values to number cause instead of making the sum will be as consider them string( for example if you type 1 , 2 , 3 , 4 without converting to number will be 1234 if you convert to number will be 10

JavaScript change value and data from value in a span

I need help with this. I need to make the value in the other place change all the time while user session is active. How can I get the value from a span and make other value in a data change?
Look at there!
1 <div class="pt-uea-container">
2 <span class="pt-uea-currency pt-uea-currency-before"> € </span>
3 <input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
4 <input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199">
5 <input type="hidden" name="pt_items[1][label]" value="Amount:">
6 <input type="hidden" name="pt_items[1][tax_percentage]" value="0">
7 <input type="hidden" name="pt_items[1][type]" value="open">
8 <div id="pt_uea_custom_amount_errors_1"></div>
9 <span class="form-price-value">85</span>
10 </div>
The value in row 9 needs to constantly change values in row 3 and 4 on the same session. Don't mind the value in row 6.
Let me know how I can get this done. Or maybe a different approach?
Greetings!
========
So this is what I got for now from you guys:
jQuery(document).ready(function($) {
var checkViewport = setInterval(function() {
var spanVal = $('.form-price-value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
}, 1000);
});
This code works, but it only affects my needs when I put my mouse in pt-field pt-uea-custom-amount and add a space in it. Then it does apply to the page source. But this is not correct. The source needs to get changed too without touching that class or a space or something!
You can easily do this with the help of jQuery.
With the help of jQuery I would do like this.
Understanding what input field needs to be tracked for changes. I will give all this field a class (track-me).
In the document ready, I will look for changes for that tracked field.
On change of that field I will get the value and put in other input fields (class copy-to - or you can do whatever you like).
See an example below,
HTML
<form>
<div class="">
<input type="text" class="track-me" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<div class="">Please type anything in the first input box</div>
</div>
</form>
jQuery
$(document).ready(function(){
$('.track-me').change(function (){
$('.copy-to').val($(this).val())
});
});
I made comments in the above jQuery code so you can understand. Also, I have made a fiddle so you can play and have a look. In this fiddle, I am using Bootstrap4 just for the purpose of styling, you don't have to worry about that.
Link to fiddle
https://jsfiddle.net/anjanasilva/r21u4fmh/21/
I hope this helps. Feel free to ask me any questions if you have. Cheers.
This is not an ideal solution. I'm not sure there is a verified way of listening for when the innerHTML of a span element changes. This sort of stuff is usually based on user interaction, and the value of the span will be modified by your page. The best solution would be to use the same method that updates the span element to update the values of you hidden input fields.
However, I've placed an interval that will run every second, that takes the text value of the span element and gives it to the values of the 2 input fields:
function start() {
setInterval(function() {
document.getElementById("pt_uea_custom_amount_1").value = document.getElementById("price_value").innerHTML;
document.getElementById("pt_uea_custom_amount_2").value = document.getElementById("price_value").innerHTML;
}, 1000);
}
window.onload = start();
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>
MutationObserver should work here..
const formValuePrice = document.querySelector( '.form-price-value' );
const inputText = document.querySelector( 'input[type="text"]' );
// timer to change values
window.setInterval( () => {
formValuePrice.textContent = Math.round( Math.random() * 100 );
}, 1000 );
// mutation observer
const observer = new MutationObserver( ( mutationsList ) => {
inputText.value = formValuePrice.textContent;
} );
observer.observe( formValuePrice, { childList: true } );
https://codepen.io/anon/pen/LgWXrz?editors=1111
try this, simple using jquery, you can check in inspect element for value attribute data-pt-price
Update: you can using jquery event .on() like change, click, keyup or else to Attach an event handler function for one or more events to the selected elements,
you can read the doc here.
here the updated code
$(function() {
var spanVal = $('#price_value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
$('#pt_uea_custom_amount_1').on('change click keyup', function() {
$('#pt_uea_custom_amount_formatted_1').val($(this).val());
$('#price_value').text($(this).val());
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>

Javascript button not working with function

I can't figure out why this function is not working. Assignment instructions call for the javascript function code to be in it's own javascript file.
Here is the html
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="submit" id="submit" value="Calculate BMI" />
</form>
Here is the function based on that form. It's supposed to calculate the bmi.
function calcBMI() {
var weight = parseInt(document.getElementByID("weight").value);
var height = parseInt(document.getElementByID("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result').value;
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
3 things:
getElementById must be in camel case. Not with capital D's at the end
Reference to textbox should be just var textbox = document.getElementById('Result') and not with .value at the end.
Button's type should be button otherwise the form is being posted.
Your working example:
function calcBMI() {
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="button" id="submit" value="Calculate BMI" />
</form>
1.
At a glance it seems as though you are not preventing the default browser behaviour, you need to use event.preventDefault() to prevent the form submitting.
function [...](e) {
e.preventDefault();
[...]
}
2.
Ensure you DOM has loaded before manipulation begins by loading the JavaScript below the HTML or you can make use of the DOMContentLoaded event.
3.
A sanity check, ensure that the script has been loaded using the <script></script> tags. If it is an external file, use the src property, if it is just code, wrap it in the aforementioned tags.
4.
You need to change the usage of getElementById you have used getElementByID instead of the lowercase d in Id.
5.
When you are doing textbox.value = result; what you are actually doing is textbox.value.value = result; as you have referenced it as .value originally.
Finally,
Make use of the console as it'll have saved you from asking here as the errors are thrown in them.
There are few problems with your function:
You have a typo in document.getElementByID, it should be document.getElementById
You have to pass an event object into your function, and invoke preventDefault, so that your form won't be submitted to the server
the line:
var textbox = document.getElementById('Result').value;
it should be
var textbox = document.getElementById('Result');
So overall, your function should look like:
function calcBMI(e) {
e.preventDefault();
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
Use on click event, change your getElementByID to getElementById and change the type to button and not submit. Submit would post it but what you need is to call the function.
<input type="button" id="submit" value="Calculate BMI" onclick="calcBMI()"/>
In your javascript change
var textbox = document.getElementById('Result').value
To
var textbox = document.getElementById('Result').value = result;
And remove
textbox.value = result;
You made a mistake here in weight and heightIt should be in camel case only.
document.getElementById("your id")
and also why not you check in console what error it shows

Why is a HTML form field showing the calculations in the output field

I've created a basic profit calculator which is pretty much working fine. My issue is that every time I enter a number into each of the relevant fields, you can see the workings out in the "Total profit" field. It first tells me my entry is NaN, then -infinity, and then shows the workings. Once I click on my calculate button, I am then finally displayed with the correct number.
For this post I am not concerned with why it is producing the NaN (not a number), but why am I seeing it populated in the field in the first place. I want this field to remain blank until I click Calculate, and then see the resulting number. I suspect it's to do with my JavaScript code but I am a complete newbie - and very stuck.
Your thoughts are most appreciative.
<form id="profitCalculator" action="" class="dark-matter">
<h1>Profit Calculator</h1>
<fieldset>
<p><label>Case Cost:<br />£
<input name="casecost" type="text" value="" size="14" maxlength="8" /></label></p>
<p><label>Units per case:<br /> <input name="packs" type="text" value="1" size="14" maxlength="8" /></label></p>
<p><label>Sell price:<br /> £ <input name="sell_price" type="text" value="" size="14" maxlength="8" /></label></p>
<p><input type="button" class="button" OnClick="Circle_calc(this.form);" value="Calculate"></p>
<p>Total Profit:<br /> £ <input name="profit" type="text" value="0" autocomplete="off" SIZE=14></p>
<p><input type="reset" class="button" value="Reset"></p>
</fieldset>
</form>
And the JavaScript
<script type="text/javascript">
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
this.elements['profit'].value = profit.toFixed(2);
}
</script>
Thank you
You've set a click handler on the form element. Since click events bubble, clicks on the elements inside the form bubble to the form as well. So that's triggering an update to your profit element on anything that any element considers a click.
This diagram from the DOM3 events spec (which has since been folded into the DOM4 spec's events section) may help clarify how bubbling works:
You have a Onclick event on your button that calls Circle_calc function.
Change your function passing the form element as a parameter, and it will work.
Circle_calc = function (form) {
var casecost = form.elements['casecost'].value || 0;
var packs = form.elements['packs'].value || 0;
var sell_price = form.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
form.elements['profit'].value = profit.toFixed(2);
}
JsFiddle here

JQuery/JavaScript: Iterate through form fields, perform calculation, then submit

Right now my code is very "hard-coded" and repetitive. I'd like to know if there is a cleaner way to do the following. Ideally, I want to iterate through my forms fields with a loop and calculate the results with one statement, but I'm struggling to figure out how best to do so.
Summary: I have ten form fields, each with a distinct decimal value that a user may or may not supply. When the user hits submit, it should add the value in the input field with a value being displayed on the current HTML page, then insert into the DB.
First, I grab that value from the form input field and convert it into a number with two decimal places. I then grab the current total from the HTML and add the two numbers together. After that I inject that total back into the form input field so that it can be stored in $_POST and inserted into a database.
How can I make my code more DRY (ie, Don't Repeat Yourself)? Below are just two examples but they are exactly the same except for the element calls:
var subtotal = Number($("#housing").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-housing').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#housing').val(total);
var subtotal = Number($("#utilities").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-utilities').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#utilities').val(total);
I would like to iterate through my input fields like so, but I'm trying to figure out how I could display the logic inside:
var input = $('.form-expenses :input');
input.each(function() {
// Insert switch statement here?? Some other construct??
});
HTML: (Uses Bootstrap 3 classes)
FORM:
<form class="form-expenses form-horizontal" role="form" method="post" action="/profile/update">
<div class="form-group">
<label for="housing" class="control-label col-sm-3">Housing</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="housing" id="housing" />
</div>
</div>
<div class="form-group">
<label for="utilities" class="control-label col-sm-3">Utilities</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="utilities" id="utilities" />
</div>
</div>
...
<button class="btn btn-lg btn-primary btn-block" id="update-expenses" type="submit"> Update</button>
</form>
OUTPUT:
<tr>
<td>Housing</td>
<td id="output-housing">$<?php echo $total['housing']?></td>
</tr>
<tr>
<td>Utilities</td>
<td id="output-utilities">$<?php echo $total['utilities']?></td>
</tr>
Something like this should work. Assumes the same prefixing relationship of output/input ID's
$(function() {
$('form.form-expenses').submit(function() {
updateValues();
return false/* prevent submit for demo only*/
})
})
function updateValues(){
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
$input.val(function(i,val){
return (1*(val ||0) + 1*curr).toFixed(2);
})
});
}
DEMO
From a UI perspective, this seems very counter intuitive to change values that user just input.
To create ajax data object instead of updating the display values:
function getAjaxData(){
var ajaxData={}
$('.form-expenses :input').not('#update-expenses').each(function(){
var $input=$(this), inputId=this.id;
var curr=$('#output-'+inputId).text().replace("$", "");
ajaxData[this.name] =(1*(val ||0) + 1*curr).toFixed(2);
});
return ajaxData
}
/* in submit handler*/
$.post('path/to/server', getAjaxData(), function(response){/*do something with reponse*/})
"if I allow a user to add/remove fields, then this could get a bit sticky"
In that case, give your fields a class name. As long as that exists on added fields, they will all be calculated.
<input type="text" class="form-control calculate-me" name="housing" id="housing" />
And iterate though all, using their ids as a reference
$(".calculate-me").each(function(){
var ref=this.id;
var subtotal = Number($("#" + ref).val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-' + ref).html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#' + ref).val(total);
});

Categories

Resources