Let say I have 2 input box to enter integer value and 1 input value for display the result of sum of 2 input box earlier.
How to make make not assigned input value default 0 integer..
Below are my code so far
<input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" id="txt3" />
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
Below are my demo.. Let say input 1 is value=1 and input 2=null, I wanna make Input 3 to be 1
http://jsfiddle.net/tLKLy/
doing
document.getElementById('txt3').value = 0
should work.
if not, this will work too
$("input:txt3").val("0");
You can add default value attribute to the input tags and it should work.
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
<input type="text" value="0" id="txt1" onkeyup="sum();" />
<input type="text" value="0" id="txt2" onkeyup="sum();" />
<input type="text" id="txt3" />
Also you could do something like this, if you don't want to see the initial zeros. Basically parse the input fields and check if the sum is a Number.
function sum() {
let num1 = +(document.getElementById('txt1').value);
let num2 = +(document.getElementById('txt2').value);
let sum = num1 + num2;
if (!isNaN(sum)) {
document.getElementById('txt3').value = sum;
}
}
<input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" id="txt3" />
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
<input type="text" id="txt1" value="0" onkeyup="sum();" />
<input type="text" id="txt2" value="0" onkeyup="sum();" />
<input type="text" id="txt3" value="0"/>
https://jsfiddle.net/VIKAS_123/yotg8d64/
Related
I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>
i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />
i want to add the first and second function value in third function.and i am using this third function value to display on one textbox.
i have tried to directly add the function and get the result but it doesnt work
i tried different function like onkeydown, onkeypress etc.
//first function
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value)
var tl = parseInt(document.getElementById("tlpw").value)
document.getElementById("ttlpw").value = tt * pp * tl;
}
//second function
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
document.getElementById("tplpw").value = tt * pp * tl;
}
//third function
function third() {
X = first();
Y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" " onkeyup="third() "
class="form-control " />
<input type="text " id="tplpw " name="tplpw "" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
This code does not give the addition of the value. I am expecting addition of x+y.
There are several issues:
Your functions first() and second() print the value, but they don't actually return those values.
On top of that, you have superfluous/random " characters and space characters which cause your inputs to not behave as expected.
Finally, you assign X and Y and then try to add x and y, but Javascript is case sensitive so the addition tries to add two undefined values.
In the below snippet (click Show to see it) I fixed all of that, and I added placeholders so at least we have some indication of what we are typing into.
As a last note, it looks like cname and nseb are not being used anywhere, also they do not have a keyup event like most of the others.
It still looks a bit messy to me; I hope it makes more sense to you.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" class="form-control " />
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
Update:
If I understand your need correctly, instead of doing onkeyup="first()" and onkeyup="second()", try changing them all to use onkeyup="third()". third() will call both the other functions, each of which will show their outcome, and then third() will show the sum of both.
Here is a new snippet that will do that. I also removed cname and nseb, and rearranged the order of inputs so they actually make sense.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
div { width: 240px; text-align: right; }
input { width: 40px; }
<div>
<input type="text" id="npt" name="npt" onkeyup="third()" /> *
<input type="text" id="divi" name="divi" onkeyup="third()" /> *
<input type="text" id="tlpw" name="tlpw" onkeyup="third()" /> =
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" /><br />
<input type="text" id="npp" name="npp" onkeyup="third()" /> *
<input type="text" id="nob" name="nob" onkeyup="third()" /> *
<input type="text" id="plpw" name="plpw" onkeyup="third()" /> =
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" /><br />
<input type="text" id="twork" name="twork" /><br />
</div>
You need that functions first and second to return the value:
function first () {
...
return tt * pp * tl
}
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("total").value = +num3 ;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p>
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.
Try this. You need to parse the input value using parseFloat. This will convert the string to a number. The existing result value is added to the newly calculating value. |0 is used for the false value of input getting 0
Updated
prev, present and total result box were added
Append each additional input with new result.
var last=0;
function multiplyBy() {
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var prev = document.getElementById("prev");
var present = document.getElementById("present");
var total = document.getElementById("result");
prev.value=last;
present.value=(parseFloat(num1.value) * parseFloat(num2.value))
last = last+(parseFloat(num1.value) * parseFloat(num2.value))
total.value=last;
num1.value = "";
num2.value = "";
}
1st Number : <input type="text" id="firstNumber" value="" /><br> 2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p >
Prev result:<br>
<input type="text" name="result" id="prev" ><br>
Present:<br>
<input type="text" name="result" id="present" ><br>
The total Result is : <br>
<input type="text" name="result" id="result"><br>
</p>
You just need for get value of text box and add it with result
function multiplyBy()
{ var sum = 0;
var num=0;
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num =parseInt(num1 * num2);
num3=parseInt(document.getElementById("result").value);
document.getElementById("result").value=(num + num3);
}
</script>
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value="0"/>
</p>
I have added the multiplyBy() to both the input fields and changed the type to number to restrict the user to enter number only.
Please check the code snippet below.
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
function multiplyBy()
{
actualResult = document.getElementById("actualResult").value ? document.getElementById("actualResult").value : 0; // Return zero if there is no value in actualResult input field
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("actualResult").value = Number(actualResult) + num3;
}
1st Number : <input type="number" id="firstNumber" value=""/><br>
2nd Number: <input type="number" id="secondNumber" value=""/><br>
<p>The Current Result is : <br>
<input type="number" name="result" id = "result" value=""/>
</p>
<p>Previous Result + Current Result : <br>
<input type="number" name="actualResult" id = "actualResult" value=""/>
</p>
You need to add event handlers if you want to calculate on change of textbox input like following.
function multiplyBy()
{
var result = document.getElementById("result");
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var num3= parseFloat(num1) * parseFloat(num2);// to convert entered values to float and || 0 to use 0 if no value is there
if(!isNaN(num3)){
document.getElementById("resultPrev").value = document.getElementById("result").value;
document.getElementById("resultCurrent").value = num3;
result.value = parseFloat(result.value || 0) + num3;
}
}
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<p>The Previous Result is : <br>
<input type="text" name="resultPrev" id = "resultPrev" value="0"/>
</p>
<p>The Current Result is : <br>
<input type="text" name="resultCurrent" id = "resultCurrent" value=""/>
</p>
<p>The Final Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
Consider handling non number values.
This question already has answers here:
How can I change div content with JavaScript?
(6 answers)
Closed 5 years ago.
I have a simple code that add two numbers. The result is displayed in a textbox. How can I display the result in a div, rather than a textbox?
Here is my current code, which displays the result in a textbox.
function sum() {
var field1 = document.getElementById('txt1').value;
var field2 = document.getElementById('txt2').value;
var field1V = parseInt(field1);
var field2V = parseInt(field2);
var result = field1V + field2V;
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
<input type="text" placeholder="Type number" id="txt1" onkeyup="sum();" />
<input type="text" placeholder="Type number" id="txt2" onkeyup="sum();" />
Result: <input type="text" id="txt3" readonly />
function sum() {
var field1 = document.getElementById('txt1').value;
var field2 = document.getElementById('txt2').value;
var field1V = parseInt(field1);
var field2V = parseInt(field2);
var result = field1V + field2V;
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
document.getElementById('result').innerHTML = result;
}
}
<input type="text" placeholder="Type number" id="txt1" onkeyup="sum();" />
<input type="text" placeholder="Type number" id="txt2" onkeyup="sum();" />
Result: <input type="text" id="txt3" readonly />
Result: <div id='result'></div>