Js String of a minus sign into a minus sign - javascript

I want to have a program that turns "-" into an actual minus sign the computer will recognize.
Here is my code:
document.getElementById("answer").innerHTML = (Number(input.substr(Number(input.indexOf("+"))).slice(1)) + Number(input.substr(0, Number(input.indexOf("+")))));

I take it you're trying to build a calculator. I'd personally create different functions for adding, subtracting, etc. You could use eval(), but that's prone to XSS.
Here's a simple calculator showcasing the minus pre-built into the JavaScript calculation, so that you don't have to worry about extracting it from the input:
function add() {
document.getElementById('answer').innerHTML = Number(document.getElementById('input1').value) + Number(document.getElementById('input2').value);
}
function subtract() {
document.getElementById('answer').innerHTML = document.getElementById('input1').value - document.getElementById('input2').value;
}
<input id="input1">
<input id="input2">
<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<div id="answer"></div>
Hope this helps! :)

Related

Calculator shows syntax error and referenceError

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cost Calculator</title>
</head>
<body>
<h1>
College Cost Calculator
</h1>
<form>
<input type= "numbers" id= "annualCost" placholder= "annual cost" />
<br>
<input type= "numbers" id= "inflationRate" placholder= "inflationRate" />
<br>
<input type= "numbers" id= "yearsUntilCollege" placholder= "yearsUntilCollege" />
<input id= "button" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>
<p id= "result">
</p>
<script>
// your code here
document.getElementById(button) = function calculator () {
let inflationRate = document.getElementById(inflationRate);
let annualCost = document.getElementById(annualCost);
let totalCost;
let annualSaving;
let yearsUntilCollege = document.getElementById(yearsUntilCollege);
totalCost = annualCost;
let amount = (inflationRate * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 2) * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 3) * annualCost) + annualCost;
totalCost += amount;
annualSaving = totalCost / 5;
return amount
return annualSaving
console.log(`For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`);
console.log(`You have to pay $${totalCost}.`);
console.log(`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`)
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
}
</script>
</body>
</html>
This is a code to calculate the college cost for Four(04) years including inflation and how much to save before college begins.
Help me figure out the issue with this code. It keeps giving syntax Error 28:15 and reference Error. I can't seem to figure out what I have done wrong and did I call the function correctly?
Many issues here:
1- Element IDs are strings. Therefore, document.getElementById expects you to pass a string to it, and strings are surrounded by quotation marks (' or ").
2- To get the value of <input> elements, you should use .value. So for example:
//get the value of input with id "inflationRate"
var inflationRate = document.getElementById("inflationRate").value;
3- To call a function on button click, use the button's onclick event, like so:
function calculator() {
//do something...
}
//call the function calculator whenever the button is clicked
document.getElementById("button").onclick = calculator;
4- As pointed out by #ecg8 in the comments, return statements jump out of the function immediately, and therefore you cannot have further statements/computations after the return statement, as they will not be reached.
And as a side note, in your HTML, numeric inputs should have a type of number and not numbers.
Edit: Also, in your last statement here:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
To concatenate these three strings into one, either wrap the entire string (all the lines) into one pair of backticks (`), or use the + operator to concatenate the strings:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
+ `You have to pay $${totalCost}.`
+ `You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`;
On a final note, all these issues are basic Javascript stuff, so I
would really recommend to study and understand the basics of
Javascript (syntax, functions, events, etc.) before solving problems
like this one.

JS Two Decimal Places .toFixed(2)

.toFixed is not working in my code. I am using it with .toLocaleString()
JS / Fiddle: https://jsfiddle.net/8b6t90f5/
$(function() {
var value = 5000.3269588;
$("#process").click(function() {
$('#amount').text("Total: $" + value.toLocaleString().toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="amount"></div>
<input id="process" class="button_text" type="submit" name="submit" value="SHOW VALUE">
Strings do not have a toFixed(), only numbers do.
$('#amount').text("Total: " + value.toLocaleString("en-US", {maximumFractionDigits:2, currency:"USD", style:"currency"}));
is possibly what you're after.
toFixed() is a Number method. toLocaleString() turns it into a string. You need to use toFixed() first, then parse that back to float and use toLocaleString():
parseFloat(value.toFixed(2)).toLocalString('en-BR');
const num = 50023.357289357;
console.log(parseFloat(num.toFixed(2)).toLocaleString());
You continue to use string methods for numbers and vice versa. Try this:
const num = 5000.3269588;
console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2}));

Why doesn't Javascript put some respeck on my input value?

I'm currently working on a budget software and I've come across this strange bug. First of here is my code:
<label class="label label-success">Choose your budget</label><br/><br/>
<div class="input-group-addon">€</div>
<input type="number" min="10" max="25000" maxlength="5" step="10" class="form-control" id="Input-budget" placeholder="Amount" onkeyup="this.value=this.value.replace(/[^\d]/,'')" onchange="budCalculate(this.value)">
this is the output line:
<li>
<strong>
Total cost: <span id="cost_eur">€0.00 </span> (<span id="cost_usd" class="small">$0.00</span>)
</strong>
</li>
Here is the Javascript:
function budCalculate(budget_amount) {
var budget = budget_amount;
cost_eur.innerHTML = "€"+((budget).toFixed(2);
cost_usd.innerHTML = "$"+ (budget * 1.13 ).toFixed(2);
}
It's supposed to put the value of the input on the output line.
The onkeyup is to prevent people from typing letters.
I've tried all kinds of variations and the funny thing is almost the same identical code is working on a similar looking page.
Why doesn't JavaScript put respeck on my value?
I suspect the issue is that budget is not a Number Object. this.value will pass a String Object. I would advise changing your function:
function budCalculate(budget_amount) {
var budget = 0;
console.log(typeof budget_amount);
budget = parseFloat(budget_amount);
cost_eur.innerHTML = "€" + budget.toFixed(2);
cost_usd.innerHTML = "$" + ( budget * 1.13 ).toFixed(2);
return budget;
}
You can now see what type of object is being passed. The parseFloat() should correct the issue.
Working Example: https://jsfiddle.net/Twisty/bqjg50sb/

Imroving the javascript code

I have a piece of code to calculate power of a number, The code is working fine for me but i am not sure if it is good performance wise.
<html>
<head>
<SCRIPT>
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
var newNumber = number;
for(var i=0; i<(power-1);i++){
newNumber *= number;
}
document.getElementById("output").innerHTML= newNumber;
}
</SCRIPT>
</head>
<body>
<input type="text" id ="number" placeholder="Enter number">
<input type="text" id ="power" placeholder="Enter power">
<input type="submit" onclick = "power()">
<p id ="output"></p>
</body>
</html>
I have changed my code to this -
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
number = Math.pow(number,power)
document.getElementById("output").innerHTML= number;
}
You can use Math.pow(base, exponent):
The Math.pow() function returns the base to the exponent Power, that
is, baseexponent.
I have to point out, that your solution using the for-loop only works when power is a positive integer. It returns a wrong value for all non-integer powers and when power < 1. That is why using Math.pow() is a wise choice.
Your code, if you dont want to use Math.pow is "optimized" you can't get better performance without using Math.pow.

Refactoring/Improving a basic JavaScript exercise -- turn a numeric score into a letter grade

So I'm about 10 hours into my programming career; bear with me please.
My attempt to solve the problem of creating a website with an HTML input area and button such that entering a number between 0 and 100 inclusive and clicking the button will take your score and return an alert box with whatever letter grade corresponds to that score is as follows:
First, the .js file
function grade() {
score = document.form1.grade.value;
if (score==100) {alert("Perfect score!");}
else if (score>=90) {alert("You got an A");}
else if (score>=80) {alert("You got a B");}
else if (score>=70) {alert("You got a C");}
else if (score>=60) {alert("You got a D");}
else {alert("Failure.");}
}
And the HTML:
<form name="form1" onsubmit="return false">
<input type="number"
name="grade"
value=""
min="0" max="100">
</form>
<input type="button" value="Grade" onclick="grade()">
I understand that this is at the level of being trivial, but just doing this simple exercise raised a ton of questions for me.
Why does the button not work if I put it within the form tags?
I tried for an unreasonably long time to get the js to work with switch. Is there a way to do it or am I doing it right with several if/else if statements?
When I didn't have onsubmit="return false" pressing enter in the text field basically borked everything, and `onsubmit="grade()" didn't work at all. Is there any way to make it so that when you enter a number (87) and press return it doesn't submit but executes the grade() function?
Any general structural improvements?
For compatibility reasons, grade is set to your input element, which is also named grade.
There is a way, but it would be quite verbose. if statements should be fine here.
Try window.grade(); return false;. The window.grade gets around the fact that plain grade is masked to the input.
You might want to learn about addEventListener. This lets you completely remove the snippets of JavaScript code (eg. onclick="window.grade(); return false;") from the HTML, leading the HTML to be cleaner. You also may want to learn about document.getElementById (which you'd use to replace document.form1.grade, which is a slightly old way of doing things).
Here's an example using addEventListener and getElementById. Have fun learning to program!
To add to icktoofay's fine (and accepted) answer, if's are just fine, but if you wanted to use a switch statement...
switch (true) {
case score == 100: alert("Perfect score!"); break;
case score >= 90: alert("You got an A"); break;
case score >= 80: alert("You got a B"); break;
case score >= 70: alert("You got a C"); break;
case score >= 60: alert("You got a D"); break;
default: alert("Failure."); break;
}
Regarding switch versus a set of if / else if / else: in most programming languages switch is intended only to match on specific values, not to match on comparisons like the greater-thans you need for your grade calculation. In JavaScript there is a way to get around that and use comparisons within the switch but I don't recommend it because the if / else if structure is already perfectly suited to that. So yes, you are doing it right.
Regarding structure, one way to make your code a little bit more flexible would be to have your function return a string that is the grade result instead of displaying it directly with alert(). That way if you later decide you want to do something else with that string instead of alerting it you don't have to change the core function. Also, I'd change it to take the score in as a parameter rather than always just calculating a grade for a specific score field.
Some examples of what I'm talking about are in the following code, noting that this isn't necessarily very good code but since you're so new I don't want to confuse things by introducing too many concepts all at once. Still, it includes some basic function parameter and string concatenation stuff. Let me know if you need an explanation of any of this.
<script>
function calculateGrade(score) {
if (score==100) { return "Perfect score!"; }
else if (score>=90) { return "You got an A"; }
else if (score>=80) { return "You got a B"; }
else if (score>=70) { return "You got a C"; }
else if (score>=60) { return "You got a D"; }
else { return "Failure."; }
}
function alertGrade(elementId) {
var score = document.getElementById(elementId).value;
var grade = calculateGrade(score);
alert("Score of " + score + ": " + grade);
}
function displayResult() {
// an example that calculateGrade's return directly instead
// of storing it in a local variable
document.getElementById('result').value = "1: "
+ calculateGrade(document.getElementById('score1').value)
+ " 2: "
+ calculateGrade(document.getElementById('score2').value);
}
</script>
<form name="form1" onsubmit="return false;">
Score 1: <input type="number" id="score1" name="score" min="0" max="100">
<input type="button" value="Alert Grade 1" onclick="alertGrade('score1')">
<br/>
Score 2: <input type="number" id="score2" name="score" min="0" max="100">
<input type="button" value="Alert Grade 2" onclick="alertGrade('score2')">
<input type="button" value="Display Both Results" onclick="displayResult()">
<input type="text" id="result" value="">
</form>

Categories