I have a basic cost calculator that I want to automatically add values as numbers are entered into the text fields. This works perfect in Chrome, but for some reason only in chrome. My goal is to have the new math results show up after the dollar sign whenever a number is entered into the text field. I am getting no console errors and JS Hint/Lint both look good.
Any ideas why this is working in chrome, but no where else?
Here is a fiddle: http://jsfiddle.net/Egreg87/j7r4zte8/4/
window.onload = function() {
$('input').keyup(function(){ // run anytime the value changes
var duration = parseFloat($('#duration').val()) || 0; // get value of field
var timeHr = parseFloat($('#timeHr').val()) || 0; // get value of field
var distance = parseFloat($('#distance').val()) || 0; // get value of field
var flight = parseFloat($('#flight').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking = '12.00';
var fuelCost= '3.50';
$('#added').html(flight + parkDays * parking + distance * (2) / (20) * fuelCost + timeHr); // add them and output it
});
$('input').keyup(function(){ // run anytime the value changes
var distance1 = parseFloat($('#distance1').val()) || 0; // get value of field
var flight1 = parseFloat($('#flight1').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking1 = '12.00';
var fuelCost1= '3.50';
$('#added1').html(flight1 + parkDays * parking1 + distance1 * (2) / (20) * fuelCost1); // add them and output it
});
$('input').keyup(function(){ // run anytime the value changes
var duration2 = parseFloat($('#duration2').val()) || 0; // get value of field
var timeHr = parseFloat($('#timeHr').val()) || 0; // get value of field
var distance2 = parseFloat($('#distance2').val()) || 0; // get value of field
var flight2 = parseFloat($('#flight2').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking2 = '12.00';
var fuelCost2= '3.50';
$('#added2').html(flight2 + parkDays * parking2 + distance2 * (2) / (20) * fuelCost2); // add them and output it
});
<!--Caclulator fields-->
<div id="calc-fields">
<div>
<label class="main3">MGM</label><br>
<label>Total Cost of Your Flight(s) from MGM $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight"></input><br />
<label for="distance">Distance (miles): </label>
<input type="text" class="number" name="distance" id="distance"></input>
<label for="duration">Drive Time (minutes): </label>
<input type="text" name="duration" id="duration" class="drive-time"></input>
<label class="main">Total Cost from MGM: <br>$</label>
<span id="added" class="main2"></span><br />
</div>
<div>
<label class="main3">ATL</label><br>
<label>Total Cost of Your Flight(s) from ATL $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight1"></input><br />
<label for="distance1">Distance (miles): </label>
<input type="text" name="distance1" id="distance1"></input>
<label for="duration1">Drive Time (minutes): </label>
<input type="text" name="duration1" id="duration1" class="drive-time"></input>
<label class="main">Total Cost from ATL:<br> $</label>
<span id="added1" class="main2"></span><br />
</div>
<div>
<label class="main3">BHM</label><br>
<label>Total Cost of Your Flight(s) from BHM $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight2"></input><br />
<label for="distance2">Distance (miles): </label>
<input type="text" name="distance2" id="distance2"></input>
<label for="duration">Drive Time (minutes):</label>
<input type="text" name="duration2" id="duration2" class="drive-time"></input>
<label class="main">Total Cost from BHM: <br>$</label>
<span id="added2" class="main2"></span><br />
</div>
<br>
<hr></hr>
<!--End calc fields-->
Couple of things- changed to document ready. You were defining a function calc1 as you were passing it as a call back, changed to anonymous function. In stead on .keyup changed to on('keyup')
If you take the time to look at console errors, things like this will never be an issue for you..
Below is fixed jsfiddle
http://jsfiddle.net/j7r4zte8/7/
$('input').on('keyup', function(){ //vs $('input').keyup(function calc1()
Related
I've recently become familiar with Jquery selectors....and they work great. Starts with...ends with....
The problem I have currently is that all of my variable names essentially start with similar patterns and end with similar patterns. This ID is generated from somewhere else so I'm hoping I can do something to use it effectively.
The pattern ID format essentially looks like...
"#id_newbudgetlineitem_set-0-line_item_october"
"#id_newbudgetlineitem_set-0-line_item_november"
"#id_newbudgetlineitem_set-0-line_item_december"
I want to essentially matching on the set-* but only if it's identical to the other ids in my array. Is this even possible without having to hard code anywhere from set-0 to set-1000? Unfortunately the class for each one is the same as is the name situation. Is there someway to say if the set numbers all match in a given array then add them up? I can't use starts with or ends with in this case...and don't want to hardcode 1000 possibilities. Thanks in advance for any ideas or thoughts.
I am trying to do something like.....
function update_total()
{
var total = 0;
$('.budget').each(function(index, element) {
"#id_newbudgetlineitem_set-0-line_item_october" +
"#id_newbudgetlineitem_set-0-line_item_november" +
"#id_newbudgetlineitem_set-0-line_item_december"
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$("#id_total").val(total);
}
Here's a working solution........
function update_total_total_total()
{
var ret = +$("input[name$='set-0-line_item_january']").val() + +$("input[name$='set-0-line_item_february']").val() + +$("input[name$='set-0-line_item_march']").val() + +$("input[name$='set-0-line_item_april']").val() + +$("input[name$='set-0-line_item_may']").val() + +$("input[name$='set-0-line_item_june']").val() + +$("input[name$='set-0-line_item_july']").val() + +$("input[name$='set-0-line_item_august']").val() + +$("input[name$='set-0-line_item_september']").val() + +$("input[name$='set-0-line_item_october']").val() + +$("input[name$='set-0-line_item_november']").val() + +$("input[name$='set-0-line_item_december']").val();
$("input[name$='set-0-line_item_total']").val(ret);
}
But I could have up to 1000 different set values. Is there some other way to do this without having to hard code this 999 more times?
This is a lot closer....but total still says 0. It's updating all of the totals to 0...so that's progress but not getting the actual totals. Forward progress thanks to Swati.
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[id$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
You can get length of total input whose name ends with line_item_total so this value will be counter for for-loop.
Then , inside for loop you can use $(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total])`) this will fetch values from all inputs expect the line_total_item then add value on each iteration .
Lastly , use $(`input[name$=set-${i}-line_item_total]`).val(total); to set total inside line_total_item textbox.
Demo Code :
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if (!isNaN(val)) {
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
update_total_total_total()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
SET 0 :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_november" value="51">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_december" value="15">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_description">
</div>
<br/>
<div>
SET 1
<input type="text" name="id_newbudgetlineitem_set-1-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_december" value="534">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-1-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_description">
</div>
<br/>
<div>
SET 2
<input type="text" name="id_newbudgetlineitem_set-2-line_item_december" value="4">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_oct" value="5">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-2-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_description">
</div>
This was the final working code. As Swati suggested it was an incorrect name reference.
function update_total_total_total() {
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
$(`input[name*=newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total);
}
}
Despite not being linked (to my knowledge), when inputting the Celsius number, the Fahrenheit formula will run and be implemented to the Celsius output, with the correct formula being outputted on the Fahrenheit output, and vice versa when inputting a Fahrenheit number.
Image
I have tried several if statements but they only seem to work for one of the outputs with the other having no value result at all.
**HTML//Bootstrap**
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">C°</span>
<input type="number" class="form-control" id="cAmount" placeholder="Celsius">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">F°</span>
<input type="number" class="form-control" id="fAmount" placeholder="Fahrenheit">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Celsius Temperature</span>
<input type="number" class="form-control" id="celsius-result" disabled>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Fahrenheit Temperature</span>
<input type="number" class="form-control" id="f-res" disabled>
</div>
</div>
**Javascript**
let formSubmit = document.querySelector('#tempCalculator')
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = celVal.toFixed(2);
fahResult.value = fahVal.toFixed(2);
//stop form refreshing
e.preventDefault();
}
Expected would be just to have one correct value appear in the corresponding output, this does happen, but an incorrect value appears in the unexpected output.
Here's a Codepen link for the full application: https://codepen.io/str-99/pen/NmwXJz
If I'm understanding you correctly this is one way to accomplish what you're trying:
let formSubmit = document.getElementById('tempCalculator');
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = Number(fahInput.value) > 0 ? celVal.toFixed(2) : '';
fahResult.value = Number(celInput.value) > 0 ? fahVal.toFixed(2) : '';
//reset input boxes
document.getElementById('cAmount').value = '';
document.getElementById('fAmount').value = '';
e.preventDefault();
}
The ternary operator works great for instances like this. We can simply change the value to an empty string when it's not the right/desired input. And for added measure clearing out the input boxes to 'reset' after each calculation.
I have a calculator. This has a form which, for certain calculations, works only when I refresh the page. Addition works but multiplication only works after refresh. Why is that?
I don't want to use JQuery!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Card Form</title>
<link href="styles/cardform.css" rel="stylesheet" type="text/css" />
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="cardform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Check Quotes</legend>
<label>Size Of the Card</label>
<label>Width in cm: </label> <input type="text" id="width" />
<label>Height in cm: </label> <input type="text" id="height" />
<br/>
<br/>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round13" onclick=""/>Standard</label>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round14" onclick="" />Toughened</label><br/>
<br/>
<label>Card: </label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round17" onclick=""/>Clear</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round18" onclick="" />Frosted</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round19" onclick="" />Leaded</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round20" onclick="" />White Bar</label>
<br/>
<label>Frame: </label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round21" onclick=""/>uPVC</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round22" onclick="" />Metal</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round23" onclick=""/>Wood</label>
<br/>
<input type="submit" value="Calculate" onClick="calculateTotal()" />
<INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()" />
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
<script>
var size1 = document.getElementById("width").value;
var size2 = document.getElementById("height").value;
var total_size = ((size1 * size2) / 10000);
var card_prices = new Array();
card_prices["Round13"] = (total_size * 67);
card_prices["Round14"] = (total_size * 87);
card_prices["Round17"] = (total_size * 0.05);
card_prices["Round18"] = (total_size * 0.65);
card_prices["Round19"] = (total_size * 0.85);
card_prices["Round20"] = (total_size * 0.95);
function getCardSizePrice2() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard1 = theForm.elements["selectedcard1"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard1.length; i++) {
//if the radio button is checked
if (selectedCard1[i].checked) {
//we set cardSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" card we set it to 25
//by using the card_prices array
//We get the selected Items value
//For example card_prices["Round8".value]"
cardSizePrice = card_prices[selectedCard1[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cardSizePrice
return cardSizePrice;
}
function getCardSizePrice3() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard2"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
function getCardSizePrice4() {
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard3"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
var divobj = document.getElementById('totalPrice');
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice2() + getCardSizePrice3() + getCardSizePrice4();
//display the result
divobj.style.display = 'block';
divobj.innerHTML = "Total Price For the Card: £" + " " + cardPrice;
displaytotal(divobj);
}
function displaytotal() {
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
function resetIt() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
</script>
</html>
I understand you've found your issue (I believe it had to do with the fact that you had your code set up with a submit button and you had totals being calculated as soon as the page load event triggered, rather than upon a click of the total button).
But, beyond that, you may still want to look at this answer very carefully as the code you have is just awful in many regards:
HTML:
Your HTML was not being used correctly. You were not using <label>
or <fieldset> elements properly.
Since you were really just needing a calculator that doesn't actually
submit the data anywhere, you shouldn't have a submit button.
You were using inline HTML event handlers (onsubmit, onclick,
etc.), which should not be used because:
They create "spaghetti code" that is difficult to read and leads to
duplication of code.
They cause global event handling wrapper functions to be implicitly
created around the attribute values that you supply that make the
binding of the this object not work as expected.
They don't follow W3C Standards for Event Handling
JavaScript:
You were setting up variables for the HTML elements you were going to
use inside your various functions, which meant that every time the
function runs, it has to re-scan the document all over again to find
the element.
You were using an array when an Object was more appropriate.
You had essentially the same function written 3 times instead of just
having it once and passing an argument to it that can change as you
need it to.
Here is a cleaned up version that follows best-practices, semantics and doesn't repeat itself. See the inline comments for specifics.
window.addEventListener("DOMContentLoaded", function(){
// Get references to DOM elements that we'll need access to just once. Don't set variables
// up to store their values at first. Set the variable to the elmement. That way, you can
// go back to the element as often as you need to in order to get any property value you
// like, without having to re-scan the document for it all over again:
var size1 = document.getElementById("width");
var size2 = document.getElementById("height");
var divObj = document.getElementById('totalPrice');
var theForm = document.getElementById("cardform");
var selectedCard1 = theForm.querySelectorAll("[name=selectedcard1]");
var selectedCard2 = theForm.querySelectorAll("[name=selectedcard2]");
var selectedCard3 = theForm.querySelectorAll("[name=selectedcard3]");
var calc = document.querySelector("input[type=button]");
var res = document.querySelector("input[type=reset]");
// Set up event handlers for various DOM elements:
calc.addEventListener("click", calculateTotal);
res.addEventListener("click", reset);
// Create a storage mechanism that holds "keys" and associated "values"
// Arrays can only do this with sequential numeric indexes. Objects, do it
// with string property names.
var card_prices = {};
// No reason to have 3 functions that all do basically the same thing but only
// to different objects. Just have one function that accepts a reference to the
// radiobuttons it needs to work with
function getCardSizePrice(cards){
var cardSizePrice = 0;
// Loop through each radio button in the passed in group
for(var i = 0; i < cards.length; i++) {
//if the radio button is checked
if(cards[i].checked) {
// Lookup the value of the selected radio button in our object and get the
// associate property value
cardSizePrice = card_prices[cards[i].value];
// No reason to continue if we get a match
break;
}
}
// We return the cardSizePrice
return cardSizePrice;
}
function calculateTotal() {
// You didn't have the following code in this funciton, so it was running immediately
// when the page loaded.
// Remember, values that you take out of form elements are strings!
// If you want to treat them as numbers, you should explicitly convert them
// to numbers first:
var s1 = parseFloat(size1.value);
var s2 = parseFloat(size2.value);
var total_size = (s1 * s2) / 10000;
// Set all the property values
card_prices["Round13"] = total_size * 67,
card_prices["Round14"] = total_size * 87,
card_prices["Round17"] = total_size * .05,
card_prices["Round18"] = total_size * .65,
card_prices["Round19"] = total_size * .85,
card_prices["Round20"] = total_size * .95,
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
// Here we get the total price by calling our function
// Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice(selectedCard1) +
getCardSizePrice(selectedCard2) +
getCardSizePrice(selectedCard3);
displayTotal(cardPrice);
}
function displayTotal(price) {
// display the result
divObj.classList.remove("hidden");
divObj.innerHTML = "Total Price For the Card: £" + " " + price.toFixed(2);
}
function reset(){
divObj.innerHTML = "";
}
});
#totalPrice { background-color:#ff0; } // Default style for element
#panel { margin-top: 1em;}
fieldset { margin-bottom:1em; }
<body>
<div id="wrap">
<form action="#" id="cardform">
<div class="cont_order">
<h1>Check Quotes</h1>
<!-- Fieldsets are for logical grouping of form elements. While they do have a
visual component to them, they are primarially for accessibility for
visually impaired. -->
<fieldset>
<legend>Size Of the Card</legend>
<!-- Labels associate with form elements via the "for" attribute and the target
element's "id" attribute. They aren't just for displaying random text.
They are a key aspect of designing for accessibility. You can click/touch the
label and activate the associated form element. -->
<label for="width">Width in cm:</label> <input type="text" id="width">
<label for="height">Height in cm:</label> <input type="text" id="height">
<br><br>
<input type="radio" name="selectedcard1" id="selectedcard1a" value="Round13">
<label for="selectedcard1a" class='radiolabel'>Standard</label>
<input type="radio" name="selectedcard1" id="selectedcard1b" value="Round14">
<label for="selectedcard1b" class='radiolabel'>Toughened</label><br>
</fieldset>
<fieldset>
<legend>Card</legend>
<input type="radio" name="selectedcard2" id="selectedcard2a" value="Round17">
<label for="selectedcard2a" class='radiolabel'>Clear</label>
<input type="radio" name="selectedcard2" id="selectedcard2b" value="Round18">
<label for="selectedcard2b" class='radiolabel'>Frosted</label>
<input type="radio" name="selectedcard2" id="selectedcard2c" value="Round19">
<label for="selectedcard2c" class='radiolabel'>Leaded</label>
<input type="radio" name="selectedcard2" id="selectedcard2d" value="Round20">
<label for="selectedcard2d" class='radiolabel'>White Bar</label>
</fieldset>
<fieldset>
<legend>Frame</legend>
<input type="radio" name="selectedcard3" id="selectedcard3a" value="Round21">
<label for="selectedcard3a" class='radiolabel'>uPVC</label>
<input type="radio" name="selectedcard3" id="selectedcard3b" value="Round22">
<label for="selectedcard3b" class='radiolabel'>Metal</label>
<input type="radio" name="selectedcard3" id="selectedcard3c" value="Round23">
<label for="selectedcard3c" class='radiolabel'>Wood</label>
</fieldset>
<div id="panel">
<input type="button" value="Calculate">
<input type="reset" value="Reset">
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;
In my form I have four fields. All fields are free to accept numbers and those numbers are converted into predefined character format (I implemented it half with bad logic but in result field it's not combining all field data into some format. Suppose if you type number 2 in every field then result field should look like : 'XXYYZZNN') ,
What I want is :
I will fix a character for each field, for T1 it's ' X ' ,for T2 it's ' Y ',
for T3 it's ' Z ' for T4 it's ' N '
Now
if i enter 2 (it can be 0-9) in T1 the result field should show 'XX'
if i enter 3 in T2 the Result field should show 'XXYYY' (hear XX is previous field data)
if i enter 1 in T3 the Result field should show 'XXYYYZ' and
if i enter 4 in T4 the Result field should show 'XXYYYZNNNN'
like wise final result will be 'XXYYYZNNNN'
How can i do this? Any help will be appreciated. Thanks.
This would be my approach:
Use data attributes to define the character for each input (also use proper label tags and type attributes for inputs)
<div>
<label for="textBox1">T1 :</label>
<input type="text" id="textBox1" data-char="X"></input>
<br/>
<label for="textBox2">T2 :</label>
<input type="text" id="textBox2" data-char="Y"></input>
<br/>
<label for="textBox3">T3 :</label>
<input type="text" id="textBox2" data-char="Z"></input>
<br/>
<label for="textBox4">T4 :</label>
<input type="text" id="textBox3" data-char="N"></input>
<br/>
<label for="message">Result :</label>
<input type="text" id="message"></input>
</div>
Then I would go through all textboxes on every keyup event, parsing their value into a number and appending the corresponding character to the result
$(document).ready(function () {
$('[id^="textBox"]').keyup(function(){
var result = '';
$('[id^="textBox"]').each(function(){
var count = parseInt($(this).val(),10) || 0;
result += Array(count+1).join($(this).data('char'));
});
$('#message').val(result);
});
});
Working fiddle
DEMO
$(document).ready(function () {
function another_format(len,char_code){
var ret='';
for(var i=0;i<len;i++){
ret +=char_code;
}
return $.trim(ret);
}
$("#textBox,#textBox1,#textBox2,#textBox3").keyup(function (event) {
console.log(event.keyCode);
if (event.keyCode >=49 && event.keyCode <= 57 && event.keyCode == 8 && event.keyCode=46) {
var x = another_format($('#textBox').val(),'X');
var y = another_format($('#textBox1').val(),'Y');
var z = another_format($('#textBox2').val(),'Z');
var n = another_format($('#textBox3').val(),'N');
$('#message').val(x+y+z+n);
}
});
});