I'm doing my Homework but I need help calculating the right way, the code I provided is what I have so far, and this is what my teacher requires: Create a webpage that contains the heading, Student Grades, and inputs a student's homework average, mid-term exam score, final exam score, and participation (all those grades will be entered as integers). Create a script that checks for valid input, i.e., that the input is between 0-100 and that, of course, the input are all numbers. If all input is valid then calculate and display the student's final average sorry for dumb question i started learning JS not to long ago
const answer = () => {
let hwNum = document.querySelector('#hwAverage');
let mtNum = document.querySelector('#midTerm');
let feNum = document.querySelector('#finalExam');
let partiNum = document.querySelector('#participation');
let answer = document.querySelector('#result')
n1 = Number(hwNum);
n2 = Number(mtNum);
n3 = Number(feNum);
n4 = Number(partiNum);
let result = (.5 * n1) + (.2 * n2) + (.2 * n3) + (.1 * n4)
answer.textContent = result
return result
};
let submit = document.querySelector('#submit').addEventListener('click', function() { answer() } )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="part1.css">
<script src="part1.js" defer></script>
<title>part 1</title>
</head>
<body>
<header>
<h1>Part 1</h1>
</header>
<br>
<label for="hwAvg"><b>Enter</b> Homework Average : </label>
<input type="number" name="hwAverage" id="hwAverage" placeholder="Enter Number 0-100">
<br>
<label for="term"><b>Enter</b> Mid-term exam score : </label>
<input type="number" name="midTerm" id="midTerm" placeholder="Enter Number 0-100">
<br>
<label for="exam"><b>Enter</b> Final exam score : </label>
<input type="number" name="finalExam" id="finalExam" placeholder="Enter Number 0-100">
<br>
<label for="partic"><b>Enter</b> Participation : </label>
<input type="number" name="participation" id="participation" placeholder="Enter Number 0-100">
<br>
<br>
<input type="button" value="SUBMIT" id="submit" class="submit">
<br>
<br>
<label for="resultLabel">Result : </label>
<div class="result" id="result"></div>
<br>
<br>
<div class="rubric">
<div class="A-tier">
<p>90-100 | A</p>
</div>
<div class="B-tier">
<p>80-89 | B</p>
</div>
<div class="C-tier">
<p>70-79 | C</p>
</div>
<div class="D-tier">
<p>60-69 | D</p>
</div>
<div class="F-tier">
<p>0-59 | F</p>
</div>
</div>
</body>
</html>**strong text**
Your solution is good.
If you want to get the data from a input element you have to use the value property.
Example:
let hwNum = document.querySelector('#hwAverage').value;
But if you want to get a element for manipulate you don't use the value property.
Example:
let answer = document.querySelector('#result');
Then if you want to set a data a input element you have to use the value property again. Example:
let hwNum = document.querySelector('#hwAverage');
hwNum.value = 'new value';
for anothers elements set value or data
let answer = document.querySelector('#result');
answer.textContent = 'new data o value';
You need to get the value of following input fields. Try this.
let hwNum = document.querySelector('#hwAverage').value;
let mtNum = document.querySelector('#midTerm').value;
let feNum = document.querySelector('#finalExam').value;
let partiNum = document.querySelector('#participation').value;
let answer = document.querySelector('#result').value;
Related
I am trying to create a loop. so far I can get it to say Hello Tom and just the number. I want to add on a function named addOrderListItems that receives the name and numOfTimes as parameters. Then call the addOrderListItems function from the displayHello function and if the number is even add an !
so if I type name Braden and numOfTimes 8
the output will display a list
1.Hello Braden
2.Hello Braden!
3.Hello Braden
4.Hello Braden!
5.Hello Braden
6.Hello Braden!
7.Hello Braden
8.Hello Braden!
9.Hello Braden
function displayHello() {
let name = document.getElementById("helloNameInput").value,
numOfTimes = document.getElementById("numOfTimesInput").value;
}
function addOrderListItems() {
let numOfTimes = 0;
while (numOfTimes > 0 ) {
document.getElementById("helloNameOutput").innerHTML = "Hello " + name + numOfTimes;
numOfTimes++;
}
}
function clearName() {
document.getElementById("helloNameInput").value = "";
document.getElementById("numOfTimesInput").value = "";
document.getElementById("helloNameOutput").innerText = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript: Looping Structures Assignment</title>
<link href="/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-3">
<h1>JavaScript: Looping Structures Assignment</h1>
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input
type="text"
class="form-control"
name="helloNameInput"
id="helloNameInput"
placeholder="Enter a name"
/>
</div>
<!--Number of Times input-->
<div class="mb-3">
<label for="numOfTimesInput" class="form-label">Number of Times:</label>
<input
type="text"
class="form-control"
name="numOfTimesInput"
id="numOfTimesInput"
placeholder="Enter number"
/>
</div>
<!--Name output-->
<ol id="helloNameOutput"></ol>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();" >
Display Hello!
</button>
<button class="btn btn-danger" id="clearButton" onclick=" clearName();">Clear</button>
</div>
<script src="/script.js"></script>
</body>
</html>
```
You'll probably need a few functions to help you accomplish your goal and keep your code organized. Below I've created an example in a code snippet to demonstrate how the functionality you described can be implemented. I've included lots of comments to explain and help you understand the steps involved.
You can search on MDN and read the JavaScript documentation if there are parts you've never seen or don't yet understand — for example, here are a few links to some of the DOM APIs used:
Document.createElement()
Element.remove()
Node.firstChild
Node.appendChild()
Keep learning, and good luck in your programming!
const nameInput = document.getElementById('helloNameInput');
const qtyInput = document.getElementById('numOfTimesInput');
const btn = document.getElementById('writeGreeting');
const output = document.getElementById('helloNameOutput');
function createGreetingText (name, withExclamationPoint) {
return `Hello ${name}${withExclamationPoint ? '!' : ''}`;
}
function createGreetingListItem (name, withExclamationPoint) {
const listItem = document.createElement('li');
listItem.textContent = createGreetingText(name, withExclamationPoint);
return listItem;
}
function clearOutput () {
// Delete every child element from the output element:
while (output.firstChild) {
output.firstChild.remove();
}
}
function writeGreeting () {
// Get the trimmed input value (or use "world" if it's empty):
const name = nameInput.value.trim() || 'world';
// Get the number of times (quantity) from the other input:
let qty = parseInt(qtyInput.value);
// If the number input value couldn't be parsed as a valid integer,
// use 1 as the default valid value and update the input:
if (!Number.isInteger(qty)) {
qty = 1;
qtyInput.value = 1;
}
clearOutput();
// Loop the number of times:
for (let i = 1; i <= qty; i += 1) {
// Create and append a list item element each time:
const isEven = i % 2 === 0;
const listItem = createGreetingListItem(name, isEven);
output.appendChild(listItem);
}
}
// Bind the "writeGreeting" function to the button's "click" event,
// so that it runs each time the button is clicked:
btn.addEventListener('click', writeGreeting);
#container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1rem;
font-family: sans-serif;
}
button, input {
font-size: 1rem;
padding: 0.5rem;
}
<div id="container">
<input
type="text"
id="helloNameInput"
placeholder="name"
value="Braden"
/>
<input
type="number"
step="1"
min="1"
id="numOfTimesInput"
placeholder="# of times"
value="8"
/>
<button id="writeGreeting">Write greeting</button>
<ol id="helloNameOutput"></ol>
</div>
Background -
I am new to JavaScript world and working on a small application to generate random number between a range. Two Inputs are taken by the user i.e. "minValue" and "maxValue" of the range and random number is generated by clicking on the "Generate" button.
Question -
How can I get the input from these two number fields when it gets updated again and again using vanilla JavaScript without any framework ?
I want to alert the user if they put the value vice versa before hitting generate button. Means if any user put minimum value in maxValue input and maximum value in minValue input. As soon as user stops I just want to make a alert for it. I know it can be done easily after hitting generate button but just for learning purpose I want to perform the operation this way.
Right now I am getting blank value of variable MinValue and maxValue at the beginning of the program and after that value is not updated by changing number field value.
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
// console.log(numberGenerator);
// console.log(button);
//console.log(minValue);
//console.log(maxValue);
let generateRandomNumber = (max, min) => {
randomNumber = Math.floor(Math.random() * (max - min)) + min
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber, minValue, maxValue);
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
Thank you
Only create variables that references the elements, ex. minInput, maxInput,
add event listeners to the elements. 'click' for the button and 'change' for the inputs,
use parseInt and store the input values in variables,
check if any of them is NaN (not a number),
generate a number of both inputs have numbers.
If I were you, I would give both the button and the .random-number span unique ids too, in order to hint that they are referenced in javascript code.
const numberGenerator = document.querySelector(".random-number");
const generateButton = document.querySelector(".button1");
const minInput = document.getElementById("min"); // 1
const maxInput = document.getElementById("max"); // 1
generateButton.addEventListener('click', generateRandomNumber); // 2
minInput.addEventListener('change', generateRandomNumber); // 2
maxInput.addEventListener('change', generateRandomNumber); // 2
function generateRandomNumber() {
let min = parseInt(minInput.value); // 3
let max = parseInt(maxInput.value); // 3
const BOTH_INPUTS_GOT_VALUES = !isNaN(min) && !isNaN(max); // 4
if (BOTH_INPUTS_GOT_VALUES) { // 5
randomNumber = Math.floor(Math.random() * (max - min)) + min;
numberGenerator.innerHTML = randomNumber;
}
}
.inputs {
margin-bottom: 1rem;
}
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value">
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value">
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
To Get The Updated Value You Have To Put
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
Inside
let generateRandomNumber = () => {...}
If You Put It Outside of generateRandomNumber then it will set the values of inputs when the page is loaded And If You Put It In The generateRandomNumber then It will reassign when that function is called
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
let generateRandomNumber = () => {
var min = document.querySelector("#min").value;
var max = document.querySelector("#max").value;
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
Update : Get The Updated Value On Input ( Before Pressing The Button )
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");
var min = 0;
var max = 0;
maxInput.oninput = valueDetected;
minInput.oninput = valueDetected;
function valueDetected(){
console.log("Max: "+maxInput.value+" & Min: "+minInput.value)
}
let generateRandomNumber = () => {
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
Validated One
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");
var min = 0;
var max = 0;
maxInput.oninput = checkValid;
minInput.oninput = checkValid;
function checkValid(){
if(parseInt(maxInput.value) < parseInt(minInput.value)){
button.style.display = "none";
error.style.display = "block";
}
else {
button.style.display = "block";
error.style.display = "none";
min = minInput.value;
max = maxInput.value;
}
}
let generateRandomNumber = () => {
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
<span class="error" style="color: red; display: none;">You Cannot Put A Maximum Value Less Than The Minimum Value</span>
</div>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
You need to add onclick event in button and call funcation.
And if you want before clicking the button then you need to add min and max textbox onchange event and write your logic
please check following way
<button class='button1' onclick="generateRandomNumber()">Generate</button>
And this your logic in funcation.
<script>
function generateRandomNumber() {
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
randomNumber = Math.floor(Math.random() * (maxValue-minValue)) + minValue
numberGenerator.innerHTML = randomNumber;
}
</script>
I am building a html form which based on that, when user submits his/her name it should return an integer representing sum of all bought items by user, the return value from API is a list of json formate, which looks like this:
[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]
This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="MyMain.css">
<script language="JavaScript">
function myFunction() {
document.getElementById('myshow').innerHTML =
document.getElementById("Name").value;
return false;
}
</script>
</head>
<body>
<div class="container">
<div>
<fieldset>
<form method="POST" action="" onSubmit="return myFunction();">
<div class="row">
<div form-group">
<label for="fname">Your Name: </label>
<input type="text" class="form-control" name="name" id="Name" placeholder="Jon" value="">
</div>
</div>
<div>
<input type="submit" class="button" value="Submit"><br/>
</div>
</div>
</form>
</fieldset>
</div>
</div>
<div class="container">
<fieldset>
<div>
<label>Prices: </label>
<p><span id='myshow'></span></p>
</div>
</fieldset>
</div>
</body>
</html>
I have no idea how to get that response and how to sum values of items!
Short answer of your question is :
var a = '[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]';
// parse your json to object if your json is string and not generated by js
a = JSON.parse(a);
var sum = 0;
Object.values(a).forEach(function(ww){
sum += Object.values(ww)[0]; // get sum of every object item value.
});
console.log(sum);
Use reduce() method in JavaScript.
let data = [{"Phone":1}, {"laptop":1}, {"car":1},{"watch":1}]
let total = data.reduce((acc, value) => {
return acc + value[Object.keys(value)[0]]
}, 0)
console.log(total);
I am trying to make a calculator for a clothing shop where the user can enter 3 prices, perform the total of these 3 prices, deduct a fidelity amount, deduct tax of 15% and display the total. What i am unable to do is to display a message which says Total is...
This is the code i've tried:
<html>
<head>
<script type="text/javascript">
function Bal(){
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
</script>
</head>
<body>
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</button>
<div id='Bal'></div>
</form>
</body>
</html>
How to display a message which says 'Total is..'
Your code works but your form is submitting and you don't see the result. To prevent that from happening use preventDefault on the click event from the button.
I've amended your code slightly to separate out the inline JS from the HTML which might make it easier to follow.
function bal(event) {
event.preventDefault();
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var add = parseInt(w) + parseInt(x) + parseInt(y);
var fid = add - parseInt(z);
var bal = fid * 0.85;
document.getElementById('bal').innerText = "Total is: " + bal;
}
const submit = document.querySelector('button');
submit.addEventListener('click', bal, false);
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button>Total</button>
<div id="bal"></div>
</form>
Further documentation
addEventListener
querySelector / querySelectorAll
The browser will reload the page when you submit the form. To prevent that default action, use event.preventDefault() as follows.
<form onsubmit="event.preventDefault()">
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</button>
<div id='Bal'></div>
</form>
Try this
<html>
<head>
</head>
<body>
<h2>Body & Soul </h2>
<form onSubmit="Bal()">
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button type="submit">Total</button>
<div id='Bal'></div>
</form>
</body>
<script type="text/javascript">
function Bal(){
event.preventDefault();
event.stopPropagation();
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
</script>
</html>
In this example, you don't have to include arguments to your function because you already grab their values within the function.
Another option would be this:
<form>
// Your code here
<button type="click" onClick="Bal()">Get Bal</button>
</form>
You should update your code with the below code.
function Bal(){
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
#total{
cursor : pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<p id="total" onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</p>
<div id='Bal'></div>
</form>
</body>
To be honest, i did not understand exactly what you mean because i copied and pasted your code into an HTML document and that worked fine :) but i guess that your problem is refreshing the page after clicking the "Total" button. am i right? for this purpose add a 'type="button"' to your button attributes to fix that. Your code is right!
I have created an HTML form with three fields. Field A for input text, and fields B and C for number input.
I created a function to calculate B i C, and to output data from A,B and C onto the page.
How can I make it so that field A must be filled in, and fields B and C must be a positive value?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tax calculator</title>
<meta charset="UTF-8">
</head>
<body>
<div>
Field A:<input id="name" type="text">
Field B:<input id="tBas" type="value">
Field C:<input id="tRat" type="value">
<button id="calc">Calculate !</button>
</div>
<strong>
<div id="name"> </div>
<div id="income"> </div>
<div id="rate"> </div>
<div id="result"> </div>
</strong>
<script src="testCalculate.js">
</script>
</body>
</html>
JavaScript:
function calculate() {
var name = document.getElementById('name').value;
var base = parseFloat(document.getElementById('tBas').value);
var rate = document.getElementById('tRat').value;
var taxPayer = ("First and last name: ") + (name);
var taxIncome = ("Income for taxation: ") + ((base).toFixed(2));
var taxRate = ("Tax rate: ") + (rate) + ("%.");
var taxToPay = ("You need to pay: ") + ((base * rate / 100).toFixed(2));
document.getElementById('name').innerHTML = taxPayer;
document.getElementById('income').innerHTML = taxIncome;
document.getElementById('rate').innerHTML = taxRate;
document.getElementById('result').innerHTML = taxToPay;
}
document.getElementById('calc').addEventListener('click', calculate);
To check if a field is filled, you can just compare his value to "".
To check if a field has a positive value, you can use parseInt to cast your value (which is a string) into an integer and then compare it to 0 > 0.
Something like that should do the trick !
function calculate() {
var name = document.getElementById('name').value;
var base = parseFloat(document.getElementById('tBas').value);
var rate = document.getElementById('tRat').value;
if (name != "" && parseInt(base) > 0 && parseInt(rate) > 0) {
var taxPayer = ("First and last name: ")+(name);
var taxIncome = ("Income for taxation: ")+((base).toFixed(2));
var taxRate = ("Tax rate: ")+(rate)+("%.");
var taxToPay = ("You need to pay: ")+((base*rate/100).toFixed(2));
document.getElementById('name').innerHTML = taxPayer;
document.getElementById('income').innerHTML = taxIncome;
document.getElementById('rate').innerHTML = taxRate;
document.getElementById('result').innerHTML = taxToPay;
}
}
document.getElementById('calc').addEventListener('click', calculate);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tax calculator</title>
<meta charset="UTF-8">
</head>
<body>
<div>
Field A:<input id="name" type="text">
Field B:<input id="tBas" type="value">
Field C:<input id="tRat" type="value">
<button id="calc">Calculate !</button>
</div>
<strong>
<div id="name"> </div>
<div id="income"> </div>
<div id="rate"> </div>
<div id="result"> </div>
</strong>
</body>
</html>
You don't need to use JS for this trick
To have the input filled set it as
<input id="name" type="text" required>
Then to have an positive value
<input id="tBas" type="number" min=0 >
IDs should be uniq. You should use another id to you div#name.
For instance, into your html code:
<div id="div_name"> </div>
And then, into your script
document.getElementById('div_name').innerHTML= taxPayer;