How to replace data in html form with JavaScript - javascript

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;

Related

How to calculate the grade the person received

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;

Program returning values as NaN

Im trying to get this program to work and i have everything running, but my values return as NaN. I've tried initializing the variables as numbers both in and outside the function to no avail. Any help?
EDIT: added in the entire script, html and all incase it helps alongside the edits suggested thus far.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Placeholder</title>
</head>
<body>
<header>
<h1>Resturant Calculator</h1>
</header>
<article>
<fieldset>
<label for="bill">
Bill Amount
</label>
<input type="number" id="bill" />
</fieldset>
<fieldset>
<label for="tip">
Tip Percent
</label>
<input type="number" id="tip" />
<label>(enter as whole number)</label>
</fieldset>
<fieldset>
<label for="peeps">
# of people
</label>
<input type="number" id="peeps" />
</fieldset>
<button id="submit" onclcick="calculate()">Calculate</button>
<p id="tipAmount">Tip Amount:</p>
<p id="total">Total Bill:</p>
<p id="totalByPeep">Total per Person:</p>
</article>
<script>
"use strict"
var bill = document.getElementById("bill").value;
var tip = document.getElementById("tip").value;
var peeps = document.getElementById("peeps").value;
var total;
var totalTip;
var tpPerson;
function calculate(){
totalTip = bill.value / (tip.value * 0.01);
total = bill.value + totalTip;
tpPerson = total / peeps.value;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + tpPerson;
}
function createEventListener(){
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener){
submitButton.addEventListener("click", calculate, false);
}
else if(submitButton.attachEvent){
submitButton.attachEvent("onclick", calculate);
}
}
if (window.addEventListener){
window.addEventListener("load", createEventListener, false);
}
else if (window.attachEvent){
window.attachEvent("onload", createEventListener);
}
</script>
</script>
</body>
</html>
You need to get the values from the elements bill,tip,peeps
Probably something like document.getElementById("bill").value
Using just document.getElementById("bill") you are selecting the element, but not its value
You need to read the value inside calculate()
function calculate(){
bill = +bill.value, tip = +tip.value, peeps = +peeps.value;
totalTip = bill/ (tip * 0.01);
total = bill + totalTip;
tpPerson = total / peeps;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + +tpPerson;
}

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

JavaScript input/output

JavaScript code is not reading my input in which is a name and should
have output saying Maurice is a very nice name. I think their is a
grammatical error that I am missing in my divOutput.
The program should take name input and output "Maurice is a very nice
name"
//text box
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em>";
divOutput.innerHTML = "is a very nice name.";
}
//end HI
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Inner.html</title>
<link rel="stylesheet" type="text/css" href="textBoxes.css" />
</head>
<body>
<h1>Inner HTML </h1>
<form action="">
<fieldset>
<label>Pleae type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
</body>
</html>
divOutput.innerHTML will replace whatever the divOutput have earlier, instead use +=.
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML += "<em>" + name + "</em>";
divOutput.innerHTML += " is a very nice name.";
}
<form action="">
<fieldset>
<label>Pleae type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
</body>
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var divOutput = document.getElementById("divOutput") ;
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> ";
divOutput.innerHTML += "is a very nice name.";
}
or
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var divOutput = document.getElementById("divOutput") ;
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> is a very nice name.";
}
Try this, you are overwriting html. Try this
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> is a very nice name.";
// divOutput.innerHTML = "is a very nice name.";
}
Take a look at this code block where I modified your attempt just a tad.
In brief, you were almost there!
Note that in order to get the value of the element, you can use .value on what was retrieved from getElementById.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Inner.html</title>
<link rel="stylesheet" type="text/css" href="textBoxes.css" />
</head>
<body>
<h1>Inner HTML</h1>
<form>
<fieldset>
<label>Please type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
<script type="text/javascript">
//text box
function sayHi() {
var txtName = document.getElementById("txtName");
console.log(txtName.value); // <== use dot value to get the value.
var divOutput = document.getElementById("divOutput");
divOutput.innerHTML =
"<em>" + txtName.value + "</em> is a very nice name.";
}
//end HI
</script>
</body>
</html>

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

Categories