If the input I put blank, then it will count 0 - javascript

I am trying to put some amount, then it will show the calculation if all input will given any number, but I want, when I do not put anything in any one of that input, then the input will count "0" automatically..
<body>
<input type='text' id='aaa'/>
<input type='text' id='bbb'/>
<input type='text' id='ccc'/>
<input type='text' id='answer' name='ans' />
<form name ="testarea" Method="GET" Action="" id='form1'>
<input type="button" onClick="Calculate();" value="calculate"/>
</form>
</body>
<script>
function Calculate()
{
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = parseFloat(aaa) * 82;
var permin1 = parseFloat(bbb) * 40;
var permin2 = parseFloat(ccc) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
document.form1.submit();
}
</script>

var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = (parseFloat(aaa)||0) * 82;
var permin1 = (parseFloat(bbb)||0) * 40;
var permin2 = (parseFloat(ccc)||0) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
You can use the OR operator to replace NaN with 0 if parseFloat returns NaN.
You could shorten the upper code to:
const ids = ["aaa","bbb","ccc"];
const factors = [82,40,10];
document.getElementById("answer").value = ids.reduce((count,id,index) => {
const { value } = document.getElementById(id);
return count + (parseFloat(value) || 0) * factors[index];
}, 0);

An alternative you can do is use a default parameter for your function.
Your calculate would look something like this:
Calculate(aaa=0, bbb, ccc) {
And this question covers how to pass html elements as parameters for functions.

Instead of using an if/else construct you can rely on the falsy value of an empty string.
Therefore you can initialize all your variables like this:
var aaa = document.getElementById('aaa').value || '0';
More information on falsy values can be found on the MDN.

Related

I stuck with this code, trying to figure out, how it should work

I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}

Convert input value into a string

So basically I am having trouble converting an input value into a string.
HTML:
<input type="text" placeholder="Email Ex: john321" id="grailedemail">
<input type="text" placeholder="Domain Ex: #gmail.com" id="graileddomain">
JS:
let email = document.getElementById("grailedemail").value;
let domain = document.getElementById("graileddomain").value;
let _ge = grailed_email.toString();
let _gd = grailed_domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
I dont know if this is the right use of .toString method.
The output of the above returns this:
{
"email":"+388321",
"pass":"password",
}
Expected Output:
{
"email":"johndoe+388321#gmail.com",
"pass":"password",
}
(I want to get whatever the user inputs)
Where before the plus there is supposed to be the variable _ge or email
And after the number, there is supposed to be the variable _gd or domain
Your problem is a typo.
The variable that contains the email is the email, and the variable that contains the domain is the domain, but you're using grailed_email and grailed_domain, and that's why the wanted data isn't in the string. Change your code to:
let grailed_email = document.getElementById("grailedemail").value; // Variable grailed_email fixed
let grailed_domain = document.getElementById("graileddomain").value; // Variable grailed_domain fixed
let _ge = grailed_email.toString();
let _gd = grailed_domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
try this way
function debug() {
var email = document.getElementById("grailedemail").value;
var domain = document.getElementById("graileddomain").value;
var _ge = email.toString();
var _gd = domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
document.getElementById('debug').textContent = emailAltered;
}
<input type="text" value="Johndoe" placeholder="Email Ex: john321" id="grailedemail">
<input type="text" value="#gmailcom" placeholder="Domain Ex: #gmail.com" id="graileddomain">
<input type="button" onclick="debug()" value="Submit">
<p id="debug"></p>

Javascript input returns NaN or undefiend

I'm making a tip calculator and I would like the tip amount to display for the user to see. The problem I'm having is the output showing up as 'NaN' or 'undefined'. I've tried making changes to my code but I keep getting the same result.
function calculateTip() {
var billInput = document.getElementById('bill');
var tipPercentage = document.getElementById('tip');
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', +tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You forgot to get the value of your fields. Because without the property .value, it returns HTMLObject.
function calculateTip() {
var billInput = parseFloat(document.getElementById('bill').value);
var tipPercentage = parseFloat(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;
};
You are reading billInput and tipPercentage as HTML element objects instead of the text the user types into them, which will be their .value properties.
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You're loading the element instead of the element value when declaring the variables billInput and tipPercentage. Try with this code:
var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;

Javascript not functioning after adding two variables

Ok, I have these input boxes.
<input
type="text"
name="amount"
class="validate[required] text-input"
id="amount">
<input type="text"
name="incfee"
id="incfee"
readonly>
And this is the javascript I have :-
<script type="text/javascript">
window.onload = function() {
var amount = document.getElementById('amount');
var incfee = document.getElementById('incfee');
var fee = 0.01;
amount.onkeyup = function() {
var result = parseFloat(amount.value) * fee;
// var result1 = result + amount;
incfee.value = !isNaN(result) ? result : '';
};
}
</script>
Now, the problem is, that if I comment the line "var result1 = result + amount;" and rename result1 to result in incfee.value , the value of the textbox (amount including fee) changes with the value in amount and everything works fine.
BUT, If I uncomment the line var result1 = result + amount; and change result to result 1 in incfee.value, the javascript doesn't works and no value is populated in the incfee textbox.
What mistake am I doing?
Thanks.
var result1 = result + parseFloat(amount.value);
Javacript doesnt know how to add a float and an input-object.
Use .value to get value of input text
var amount = document.getElementById('amount').value;
var incfee = document.getElementById('incfee').value;

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

Categories

Resources