I want to reset my value inputs, Calculated Grade and also getElementById("an"), getElementById("and"). I've been trying various different methods and nothing seems to work. I also tried using forms method and my code seems to crash.
please help!
I have the following code(everything works except for reset button):
document.getElementById("button").onclick = function() {
var a = document.getElementById("1").value * 0.4;
var b = document.getElementById("2").value * 0.4;
var c = document.getElementById("3").value * 0.2;
var grade = a + b + c;
document.getElementById("ans").innerHTML = grade;
if (grade < 70) {
document.getElementById("and").innerHTML = "bad"
} else if (grade >= 70) {
document.getElementById("an").innerHTML = "good"
}
document.div[1].addEventListener('reset', function() {
document.getElementById('and', 'an', 'ans').innerHTML = '';
});
}
.legend {
position: relative;
width: 100%;
display: block;
padding: 20px;
border-radius: 20px;
background: #FFFF50;
padding: 15px;
color: black;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
}
.wrapper {
border: 1px dashed #95a5a6;
height: 56px;
margin-top: 16px;
border-radius: 4px;
position: relative;
font-size: 20px;
}
.wrapper p {
line-height: 31px;
}
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<div id="myForm">
<p>
What's Your First Grade?<input type="text" id="1" placeholder="Input 1st #"><br> What About Your Second Grade? <input type="text" id="2" placeholder="Input 2st #"><br> And Third? <input type="text" id="3" placeholder="Almost there 3rd #">
</p>
<button id="button">Calculate</button>
<button onclick="myFunction()">Reset</button>
</div>
<p>
Calculated Grade: <span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p> <span id="an" style="color: green;"></span> <span id="and" style="color: red;"></span></p>
</div>
</div>
Define your myFunction:
function myFunction(){
document.getElementById('and','an','ans').innerHTML = '';
}
Add calculate as a function instead of adding onclick event listener to each button in page.
<button id="button" onclick="calculate()">Calculate</button>
getElementById() only supports one name at a time and only returns a single node not an array of nodes.
<!DOCTYPE html>
<html>
<body>
<style>
.legend {
position: relative;
width: 100%;
display: block;
padding: 20px;
border-radius: 20px;
background: #FFFF50;
padding: 15px;
color: black;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
}
.wrapper {
border: 1px dashed #95a5a6;
height: 56px;
margin-top: 16px;
border-radius: 4px;
position: relative;
font-size: 20px;
}
.wrapper p {
line-height: 31px;
}
</style>
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<div id="myForm">
<p>
What's Your First Grade?<input type="text" id="1" placeholder="Input 1st #"><br> What About Your Second Grade? <input type="text" id="2" placeholder="Input 2st #"><br> And Third? <input type="text" id="3" placeholder="Almost there 3rd #">
</p>
<button id="button" onclick="calculate()">Calculate</button>
<button onclick="myFunction()">Reset</button>
</div>
<p>
Calculated Grade: <span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p> <span id="an" style="color: green;"></span> <span id="and" style="color: red;"></span></p>
</div>
</div>
<script>
function calculate() {
var a = document.getElementById("1").value * 0.4;
var b = document.getElementById("2").value * 0.4;
var c = document.getElementById("3").value * 0.2;
var grade = a + b + c;
document.getElementById("ans").innerHTML = grade;
if (grade < 70) {
document.getElementById("and").innerHTML = "bad"
} else if (grade >= 70) {
document.getElementById("an").innerHTML = "good"
}
}
function myFunction() {
document.getElementById('and').innerHTML = '';
document.getElementById("ans").innerHTML = '';
document.getElementById("an").innerHTML = '';
}
</script>
</body>
</html>
Try this function I hope it May work.
function myFunction(){
document.getElementById("1").value=0;
document.getElementById("2").value=0;
document.getElementById("3").value=0;
document.getElementById('ans').innerHTML = "0";
document.getElementById('and').innerHTML = '';
document.getElementById('an').innerHTML = '';
}
I would suggest to change your html to have a form for example
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<form id="myForm">
<p>
What's Your First Grade?
<input type="text" id="1" placeholder="Input 1st #" />
<br/> What About Your Second Grade?
<input type="text" id="2" placeholder="Input 2st #" />
<br/> And Third?
<input type="text" id="3" placeholder="Almost there 3rd #" />
</p>
<button id="button">Calculate</button>
<button onclick="myFunction()">Reset</button>
</form>
<div class="answer">
<p>Calculated Grade:
<span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p>
<span id="an" style="color: green;"></span>
<span id="and" style="color: red;"></span>
</p>
</div>
</div>
</div>
Then you can use form reset in javascript as follow:
function calculate() {
document.getElementById('myForm').reset();
}
Related
In the snippet below, I have a step-form. While submitting the content in the form and hitting next, the input values are being passed to the confirmation page at the end.
I'm trying to understand if this is the most efficient way to pass the information to the confirmation page?
const previousButton = document.getElementById("previous")
const nextButton = document.getElementById("next")
const submitButton = document.getElementById('validate')
const form = document.getElementById('stepByStepForm')
const dots = document.getElementsByClassName('progress-bar__dot')
const numberOfSteps = 5
let currentStep = 1
for(let i = 0 ; i < dots.length ; ++i){
dots[i].addEventListener('click', ()=>{
goToStep(i+1)
})
}
previousButton.onclick = goPrevious
nextButton.onclick = goNext
function goNext(e) {
e.preventDefault()
currentStep += 1
goToStep(currentStep)
}
function goPrevious(e) {
e.preventDefault()
currentStep -= 1
goToStep(currentStep)
}
function goToStep(stepNumber){
currentStep = stepNumber
let inputsToHide = document.getElementsByClassName('step')
let inputs = document.getElementsByClassName(`step${currentStep}`)
let indicators = document.getElementsByClassName('progress-bar__dot')
for(let i = indicators.length-1; i >= currentStep ; --i){
indicators[i].classList.remove('full')
}
for(let i = 0; i < currentStep; ++i){
indicators[i].classList.add('full')
}
//hide all input
for (let i = 0; i < inputsToHide.length; ++i) {
hide(inputsToHide[i])
}
//only show the right one
for (let i = 0; i < inputs.length; ++i) {
show(inputs[i])
}
//if we reached final step
if(currentStep === numberOfSteps){
enable(previousButton)
disable(nextButton)
show(submitButton)
}
//else if first step
else if(currentStep === 1){
disable(previousButton)
enable(next)
hide(submitButton)
}
else {
enable(previousButton)
enable(next)
hide(submitButton)
}
}
function enable(elem) {
elem.classList.remove("disabled");
elem.disabled = false;
}
function disable(elem) {
elem.classList.add("disabled");
elem.disabled = true;
}
function show(elem){
elem.classList.remove('hidden')
}
function hide(elem){
elem.classList.add('hidden')
}
//collect inputs
next.addEventListener('click', function() {
const fNameInput = document.getElementById('firstname').value;
document.getElementById('fNameOutput').textContent = fNameInput;
const lNameInput = document.getElementById('lastname').value;
document.getElementById('lNameOutput').textContent = lNameInput;
const emailInput = document.getElementById('mail').value;
document.getElementById('emailOutput').textContent = emailInput;
const phoneInput = document.getElementById('phone').value;
document.getElementById('phoneOutput').textContent = phoneInput;
const addressInput = document.getElementById('address').value;
document.getElementById('addressOutput').textContent = addressInput;
const countryInput = document.getElementById('country').value;
document.getElementById('countryOutput').textContent = countryInput;
const colorInput = document.getElementById('color').value;
document.getElementById('colorOutput').textContent = colorInput;
const animalInput = document.getElementById('animal').value;
document.getElementById('animalOutput').textContent = animalInput;
});
submitButton.addEventListener('click', function(e) {
e.preventDefault();
})
html {
background-color: #A2C7E5;
}
.hidden {
display: none;
}
.button {
width: 140px;
cursor: pointer;
padding: 1em;
border-radius: 0.2em;
border: none;
color: white;
font-weight: bold;
font-size: 1em;
transition: all 0.5s ease;
background-color: #ff8552;
}
.button:hover {
background-color: #ff4f06;
}
.button.disabled {
opacity: 0.5;
}
.button.disabled:hover {
background-color: #ff8552;
}
.form {
width: 20em;
margin: auto;
margin-top: 5em;
padding: 5em;
padding-top: 2em;
padding-bottom: 2em;
background-color: white;
font-family: "Raleway", sans-serif;
color: #33312E;
border-radius: 0.2em;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}
.form .progress-bar {
width: 100%;
list-style-type: none;
display: flex;
padding: 0;
justify-content: center;
margin-bottom: 3.5em;
}
.form .progress-bar li.progress-bar__dot {
display: block;
width: 0.6em;
border-radius: 50%;
height: 0.6em;
border: 0.1em solid #ff8552;
background-color: white;
cursor: pointer;
transition: all 0.5s ease;
}
.form .progress-bar li.progress-bar__dot.full {
background-color: #ff8552;
}
.form .progress-bar li.progress-bar__connector {
display: block;
width: 5em;
border-radius: 1000em;
height: 0.1em;
background-color: #ff8552;
margin-top: 0.35em;
}
.form label {
font-weight: bold;
font-size: 1.2em;
}
.form input {
width: 100%;
padding: 1.3em;
margin-bottom: 3em;
box-sizing: border-box;
margin-top: 1em;
border: none;
border-radius: 0.5em;
background-color: #e6e6e6;
font-size: 1em;
font-family: "Raleway", sans-serif;
}
.form input:focus {
border: none;
}
.form .button-group {
width: 100%;
display: flex;
justify-content: space-between;
margin-top: 50px;
}
.form button#validate {
margin: auto;
background-color: #1A936F;
width: 12em;
}
.form button#validate:hover {
background-color: #12684e;
}
<form id="stepByStepForm" class="form">
<ul class="progress-bar">
<li class="progress-bar__dot full"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
</ul>
<div class="step step1">
<div class="input-group">
<label for="firstname">First name</label>
<input type="text" value="James" name="firstname" id="firstname">
</div>
<div class="input-group">
<label for="lastname">Last name</label>
<input type="text" value="Smith" name="lastname" id="lastname">
</div>
</div>
<div class="step step2 hidden">
<div class="input-group">
<label for="mail">E-mail</label>
<input type="mail" value="jamessmith#gmail.com" name="mail" id="mail">
</div>
<div class="input-group">
<label for="phone">Phone</label>
<input type="text" value="602-379-1395" name="phone" id="phone">
</div>
</div>
<div class="step step3 hidden">
<div class="input-group">
<label for="address">Address</label>
<input type="text" value="221B Baker Street" name="address" id="address">
</div>
<div class="input-group">
<label for="country">Country</label>
<input type="text" value="United States" name="country" id="country">
</div>
</div>
<div class="step step4 hidden">
<div class="input-group">
<label for="color">Favorite Color</label>
<input type="text" value="Blue" name="color" id="color">
</div>
<div class="input-group">
<label for="animal">Favorite Animal</label>
<input type="text" value="Lion" name="animal" id="animal">
</div>
</div>
<div class="step step5 hidden">
<h4>Name:</h4>
<p><strong>First Name:</strong> <span id="fNameOutput"></span></p>
<p><strong>Last Name:</strong> <span id="lNameOutput"></span></p>
<hr>
<h4>Contact:</h4>
<p><strong>Email:</strong> <span id="emailOutput"></span></p>
<p><strong>Phone:</strong> <span id="phoneOutput"></span></p>
<hr>
<h4>Location:</h4>
<p><strong>Address:</strong> <span id="addressOutput"></span></p>
<p><strong>Country:</strong> <span id="countryOutput"></span></p>
<hr>
<h4>Attributes:</h4>
<p><strong>Favorite Color:</strong> <span id="colorOutput"></span></p>
<p><strong>Favorite Animal:</strong> <span id="animalOutput"></span></p>
</div>
<div class="button-group">
<button id="previous" class="disabled button" disabled>
previous
</button>
<button id="next" class="button">
next
</button>
</div>
<div class="button-group">
<button id="validate" type="submit" class="hidden button">
Submit
</button>
</div>
</form>
There are 3 problems:
In this part next.addEventListener('click', function() {...}, it updates all texts every time the next button is pressed.
document.getElementById(ID_NAME).textContent = VALUE; is written repeatedly; It is not that bad but there are more readable ways.
The confirmation textContents are not updated when the last dot is clicked.
First, make a function to update texts. To avoid writing similar code repeatedly, you can use an Object for ids and for...of to implement updating the text contents.
function updateConfirmText() {
const map = {
firstname: 'fNameOutput',
lastname: 'lNameOutput',
mail: 'emailOutput',
phone: 'phoneOutput',
address: 'addressOutput',
country: 'countryOutput',
color: 'colorOutput',
animal: 'animalOutput'
};
for (const [input, output] of Object.entries(map)) {
document.getElementById(output).textContent = document.getElementById(input).value;
}
}
Second, call the function in the if statement that you have already written.
//if we reached final step
if (currentStep === numberOfSteps) {
enable(previousButton)
disable(nextButton)
show(submitButton)
updateConfirmText(); // Add
}
I hope it works🤞
So I have made a function which changes my values in a "cart". Every input field has their one value and this is added or substracted on it's total on change of the input field. It looks like this:
And my code looks like this (yes I am gonna cleanup the html+css later, this is just for testing :-):
var extraValues = document.querySelectorAll("input[type=number]");
var extraTotal = 0;
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
})
});
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
This works perfectly. But now I need to calculate the total amount of these 3 values each time one of the inputs changes, and show it in id="totalPrice". I have NO idea how to do this, since everytime I try this it just replaced the total pricing instead of adding or substracting it from the total. Does anyone know how to do this?
Try this Code man thanks :-)
function countProperties(obj) {
var count = 0;
for(var prop in obj) {
console.log(prop,obj)
if(obj.hasOwnProperty(prop))
count = count +obj[prop];
}
return count;
}
var total = {}
var extraValues = document.querySelectorAll("input[type=number]");
var extraTotal = 0;
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
total[catId] = totalPrice
// var TotalCost = Object.values(total).reduce((a, b) //=> a + b, 0)
var TotalCost = countProperties(total)
console.log(TotalCost)
alert(TotalCost)
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
})
});
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
Solution
In this solution I have added a function to calculate the sum.
So when the value changes then I call at the end of your function.
The calculator which calculates the sum and insert it inside your text field.
var extraValues = document.querySelectorAll("input[type=number]");
// extraValues.forEach((elem)=>{
// elem.addEventListener('input', function (evt) {
// calculator();
// })
// });
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
calculator()
})
});
function calculator(){
let prices = document.querySelectorAll('.extraPrice')
let sum = 0;
let fac = 0;
extraValues.forEach((elem, ind) =>{
fac = parseFloat(prices[ind].innerHTML)
sum += parseInt(elem.value) * fac;
})
document.getElementById("totalPrice").innerHTML = sum;
}
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
I'm making a calculator that will take inputs from a survey form and then push results to an object so I can display it on other parts of the site and use chart.js
However, I can't get the first calculation to work. My first function is to calculate the 30% saving of monthly gas spend (gas) and to subtract the saving from a monthly payment (price). I'm getting NaN in the console when the site loads even before clicking the button which has the eventlistener assigned to it.
Where am I going wrong?
P.S I haven't made the form responsive yet so it will need to be viewed in a full browser.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc());
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>
calculate.addEventListener('click', calc());
to
calculate.addEventListener('click', calc);
the calc() with parentheses will execute the function directly, whilst without it will only be called upon.
Also, you should add an event prevent default to not having the page refreshed.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc(event) {
// Prevent page refresh.
event.preventDefault();
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
I have tried to solve the issue: Please check
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>
Hope, it will help you
Step #1
I added jquery reference in the head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Step #2
I added onclick event to call calc() function
Calculate
Step #3
I added this script now it's working fine
function calc() {
debugger
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
What I understand your are not properly calling the event that's why NAN(Not a Number) is appearing in the console and the second thing you asked in the comment about round off it is very simple
https://www.w3schools.com/JSREF/jsref_round.asp
please check this link it will help you
The calculator was working fine until I added the activity level from the drop down. Depending on the users selection for activity level, the value returned should be multiplied by the corresponding value associated with each activity level. I have added the values that it should be multiplying the result by. However, it doesn't seem to be seeing the 'activityLevel' variable inside the function. Am I not declaring this properly? When I try to run the code, it returns a NaN result.
/* Calculate female macros */
(function() {
function calculateFemale(femaleWeight, femaleHeight, femaleAge) {
femaleWeight = parseFloat(femaleWeight);
femaleHeight = parseFloat(femaleHeight);
femaleAge = parseFloat(femaleAge);
activityLevel = (activityLevel);
return (((femaleWeight * 4.3) + (femaleHeight * 4.7) - (femaleAge * 4.7) * activityLevel);
}
var womanBMR = document.getElementById("womanBMR");
if (womanBMR) {
womanBMR.onsubmit = function() {
this.result.value = calculateFemale(this.femaleWeight.value, this.femaleHeight.value, this.femaleAge.value, this.activityLevel.value);
return false;
};
}
}());
/* Calculate male macros */
(function() {
function calculateMale(maleWeight, maleHeight, maleAge) {
maleWeight = parseFloat(maleWeight);
maleHeight = parseFloat(maleHeight);
maleAge = parseFloat(maleAge);
activityLevel = (activityLevel);
return (((maleWeight * 6.3) + (maleHeight * 12.9) - (maleAge * 6.8) + 66) * activityLevel);
}
var maleBMR = document.getElementById("manBMR");
if (manBMR) {
manBMR.onsubmit = function() {
this.result.value = calculateMale(this.maleWeight.value, this.maleHeight.value, this.maleAge.value, this.activityLevel.value);
return false;
};
}
}());
* {
box-sizing: border-box;
}
img {
max-width: 100%;
}
.w-button {
display: inline-block;
padding: 9px 15px;
background-color: #3898EC;
color: white;
border: 0;
border-radius: 0;
}
p {
margin-top: 0;
margin-bottom: 10px;
}
.w-container {
margin-left: auto;
margin-right: auto;
max-width: 940px;
}
.w-row:before,
.w-row:after {
content: " ";
display: table;
}
.w-row:after {
clear: both;
}
.w-col {
position: relative;
float: left;
width: 100%;
min-height: 1px;
padding-left: 10px;
padding-right: 10px;
}
.w-col .w-col {
padding-left: 0;
padding-right: 0;
}
.w-col-1 {
width: 8.33333333%;
}
.w-col-2 {
width: 91.66666667%;
}
body {
margin: 0;
background-color: #fff;
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
h1 {
font-size: 38px;
line-height: 44px;
margin-top: 20px;
}
h2 {
margin-top: 20px;
margin-bottom: 10px;
color: #f70909;
font-size: 32px;
line-height: 36px;
font-weight: 400;
}
.text-block {
position: relative;
left: 100px;
}
.text-block-3 {
margin-top: 20px;
padding-left: 100px;
}
.text-block-4 {
padding-top: 20px;
padding-left: 20px;
}
.list {
padding-left: 140px;
}
.div-block {
font-style: italic;
font-weight: 400;
}
.paragraph {
padding-top: 20px;
}
.container {
margin-top: 0px;
}
.button {
margin-top: 20px;
margin-left: 100px;
background-color: #020202;
}
.column-1 {
background-color: #f0e8e8;
}
.image {
padding-left: 20px;
}
<!DOCTYPE html>
<head>
<title>Calculator</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="w-row">
<div class="w-col w-col-1"><img src="images/apple.jpg" alt="apple"></div>
<div class="column-1 w-col w-col-2">
<h1>Healthy Eating</h1>
</div>
</div>
<div class="w-container">
<h2>Calculator</h2>
</div>
<div class="w-container">
<div><em>Use the form below if you are female.</em></div>
<form id="womanBMR">
<fieldset>
<p>
<label for="femaleWeight">Weight (lbs)</label>
<input id="femaleWeight" name="femaleWeight" type="number" />
</p>
<p>
<label for="femaleHeight">Height (inches)</label>
<input id="femaleHeight" name="femaleHeight" type="number" />
</p>
<p>
<label for="femaleAge">Ages (years)</label>
<input id="femaleAge" name="femaleAge" type="number" />
</p>
<p>
<select id = "selActivity">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<div class="w-container">
<div><em>Use the form below if you are male.</em></div>
<form id="manBMR">
<fieldset>
<p>
<label for="maleWeight">Weight (lbs)</label>
<input id="maleWeight" name="maleWeight" type="number" />
</p>
<p>
<label for="maleHeight">Height (inches)</label>
<input id="maleHeight" name="maleHeight" type="number" />
</p>
<p>
<label for="maleAge">Ages (years)</label>
<input id="maleAge" name="maleAge" type="number" />
</p>
<p>
<select id = "activityLevel">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<script src="js/calculatorscript.js"></script>
HomeRecipesTipsFAQ
</body>
</html>
You forgot to add the parameter to the function definition and to call parseFloat
/* Calculate female macros */
(function() {
function calculateFemale(femaleWeight, femaleHeight, femaleAge) {
femaleWeight = parseFloat(femaleWeight);
femaleHeight = parseFloat(femaleHeight);
femaleAge = parseFloat(femaleAge);
return ((femaleWeight * 4.3) + (femaleHeight * 4.7) - (femaleAge * 4.7) + 655);
}
var womanBMR = document.getElementById("womanBMR");
if (womanBMR) {
womanBMR.onsubmit = function() {
this.result.value = calculateFemale(this.femaleWeight.value, this.femaleHeight.value, this.femaleAge.value);
return false;
};
}
}());
/* Calculate male macros */
//*This function calculates the macros for a male, it requires three variables be input
//*by the user. Their weight, height, and age. It then returns the
(function() {
function calculateMale(maleWeight, maleHeight, maleAge, activityLevel) {
maleWeight = parseFloat(maleWeight);
maleHeight = parseFloat(maleHeight);
maleAge = parseFloat(maleAge);
activityLevel = parseFloat(activityLevel);
return (((maleWeight * 6.3) + (maleHeight * 12.9) - (maleAge * 6.8) + 66) * activityLevel);
}
var maleBMR = document.getElementById("manBMR");
if (manBMR) {
manBMR.onsubmit = function() {
this.result.value = calculateMale(this.maleWeight.value, this.maleHeight.value, this.maleAge.value, this.activityLevel.value);
return false;
};
}
}());
* {
box-sizing: border-box;
}
img {
max-width: 100%;
}
.w-button {
display: inline-block;
padding: 9px 15px;
background-color: #3898EC;
color: white;
border: 0;
border-radius: 0;
}
p {
margin-top: 0;
margin-bottom: 10px;
}
.w-container {
margin-left: auto;
margin-right: auto;
max-width: 940px;
}
.w-row:before,
.w-row:after {
content: " ";
display: table;
}
.w-row:after {
clear: both;
}
.w-col {
position: relative;
float: left;
width: 100%;
min-height: 1px;
padding-left: 10px;
padding-right: 10px;
}
.w-col .w-col {
padding-left: 0;
padding-right: 0;
}
.w-col-1 {
width: 8.33333333%;
}
.w-col-2 {
width: 91.66666667%;
}
body {
margin: 0;
background-color: #fff;
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
h1 {
font-size: 38px;
line-height: 44px;
margin-top: 20px;
}
h2 {
margin-top: 20px;
margin-bottom: 10px;
color: #f70909;
font-size: 32px;
line-height: 36px;
font-weight: 400;
}
.text-block {
position: relative;
left: 100px;
}
.text-block-3 {
margin-top: 20px;
padding-left: 100px;
}
.text-block-4 {
padding-top: 20px;
padding-left: 20px;
}
.list {
padding-left: 140px;
}
.div-block {
font-style: italic;
font-weight: 400;
}
.paragraph {
padding-top: 20px;
}
.container {
margin-top: 0px;
}
.button {
margin-top: 20px;
margin-left: 100px;
background-color: #020202;
}
.column-1 {
background-color: #f0e8e8;
}
.image {
padding-left: 20px;
}
<!DOCTYPE html>
<head>
<title>Calculator</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="w-row">
<div class="w-col w-col-1"><img src="images/apple.jpg" alt="apple"></div>
<div class="column-1 w-col w-col-2">
<h1>Healthy Eating</h1>
</div>
</div>
<div class="w-container">
<h2>Calculator</h2>
</div>
<div class="w-container">
<div><em>Use the form below if you are female.</em></div>
<form id="womanBMR">
<fieldset>
<p>
<label for="femaleWeight">Weight (lbs)</label>
<input id="femaleWeight" name="femaleWeight" type="number" />
</p>
<p>
<label for="femaleHeight">Height (inches)</label>
<input id="femaleHeight" name="femaleHeight" type="number" />
</p>
<p>
<label for="femaleAge">Ages (years)</label>
<input id="femaleAge" name="femaleAge" type="number" />
</p>
<p>
<select id = "selActivity">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<div class="w-container">
<div><em>Use the form below if you are male.</em></div>
<form id="manBMR">
<fieldset>
<p>
<label for="maleWeight">Weight (lbs)</label>
<input id="maleWeight" name="maleWeight" type="number" />
</p>
<p>
<label for="maleHeight">Height (inches)</label>
<input id="maleHeight" name="maleHeight" type="number" />
</p>
<p>
<label for="maleAge">Ages (years)</label>
<input id="maleAge" name="maleAge" type="number" />
</p>
<p>
<select id = "activityLevel">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<script src="js/calculatorscript.js"></script>
HomeRecipesTipsFAQ
</body>
</html>
I'm making a printable ICE card. User enters info in form inputs and they are shown preview below.
The code I have is working fine, but I have to copy/paste it for each input/element match. I want to compress the code so that it listens for changes for each input and changes the text for matching element.
Snippet below. JSFiddle is here
$("#inputName").keyup(function() {
$("#spanName").html($(this).val());
});
$("#inputHCN").keyup(function() {
$("#spanHCN").html($(this).val());
});
$("#inputDOB").keyup(function() {
$("#spanDOB").html($(this).val());
});
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</p>
<p>
<input type="text" name="inputHCN" class="form-control" id="inputHCN" placeholder="Health Card #">
</p>
<p>
<input type="text" name="inputDOB" class="form-control" id="inputDOB" placeholder="D.O.B.">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
Data attributes is the way I would go
$("[data-out]").keyup(function() {
var selector = $(this).data("out");
$(selector).text($(this).val());
});
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name" data-out="#spanName">
</p>
<p>
<input type="text" name="inputHCN" class="form-control" id="inputHCN" placeholder="Health Card #" data-out="#spanHCN">
</p>
<p>
<input type="text" name="inputDOB" class="form-control" id="inputDOB" placeholder="D.O.B." data-out="#spanDOB">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
Add data-target attribute to your form elements with ids of elements where the text should be displayed:
<input type="text" name="inputName" data-target="#spanName" class="form-control" id="inputName" placeholder="Name">
Now change your scripts to display the text. Note that I am using two events keyup and change so that copy-paste would work as well.
$(".form-control").on('keyup change', function(e) {
var target = $(this).data("target");
$(target).html($(this).val());
});
Demo shown below:
$(".form-control").on('keyup change', function(e) {
var target = $(this).data("target");
$(target).html($(this).val());
});
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="inputName" data-target="#spanName" class="form-control" id="inputName" placeholder="Name">
</p>
<p>
<input type="text" name="inputHCN" data-target="#spanHCN" class="form-control" id="inputHCN" placeholder="Health Card #">
</p>
<p>
<input type="text" name="inputDOB" data-target="#spanDOB" class="form-control" id="inputDOB" placeholder="D.O.B.">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
There could be a lot of variants, here is a short one that rely to keep a naming convention between input id attribute and span id attribute:
$("#inputName,#inputHCN,#inputDOB").keyup(function() {
$("#span" + this.id.replace('input', '')).html($(this).val());
});
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</p>
<p>
<input type="text" name="inputHCN" class="form-control" id="inputHCN" placeholder="Health Card #">
</p>
<p>
<input type="text" name="inputDOB" class="form-control" id="inputDOB" placeholder="D.O.B.">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
Another way is through replacing input with span assuming that the naming convention is followed.
$("#inputName, #inputHCN, #inputDOB").keyup(function() {
var spanId = $(this).attr("id").replace("input", "span");
$("#" + spanId).html($(this).val());
});
You can try this. Hope it will help. Just change the name of textboxes and find the span control using textbox name.
$("#inputName,#inputHCN,#inputDOB").keyup(function() {
var inputValue = $(this).attr("name");
$("#span" + inputValue).html($(this).val());
});
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="Name" class="form-control" id="inputName" placeholder="Name">
</p>
<p>
<input type="text" name="HCN" class="form-control" id="inputHCN" placeholder="Health Card #">
</p>
<p>
<input type="text" name="DOB" class="form-control" id="inputDOB" placeholder="D.O.B.">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
You could loop through inputs and add event listeners to each:
var inputs = $('form p input');
for (var i=0; i<inputs.length; i++) {
$(inputs[i]).keyup(function() {
var span = $(this).attr('id').replace('input','span');
$("#"+span).html($(this).val());
});
}
* {
margin: 0;
outline: 0;
box-sizing: border-box;
font-family: 'Segoe UI', 'Open Sans', 'Roboto', sans-serif;
}
div {
background: #fff;
height: 54mm;
width: 100mm;
border-width: 2px;
border-style: dashed;
border-radius: 2.88mm;
padding: 10px;
margin: 0 auto;
position: relative;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
li {
color: blue;
}
span[id*="span"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</p>
<p>
<input type="text" name="inputHCN" class="form-control" id="inputHCN" placeholder="Health Card #">
</p>
<p>
<input type="text" name="inputDOB" class="form-control" id="inputDOB" placeholder="D.O.B.">
</p>
etc...
</form>
<br />
<h4>
Preview of your printable card
</h4>
<br />
<div>
<ul>
<li>Name: <span id="spanName"></span></li>
<li>Health Card #: <span id="spanHCN"></span></li>
<li>D.O.B.: <span id="spanDOB"></span></li>
<li>etc...</li>
</ul>
</div>
//map the names of the input elements with the output elements
var myIOMap={
inputName:"spanName",
inputHCN:"spanHCN",
inputDOB:"spanDOB",
};
function doTextBinding(ioMap){
Object.keys(ioMap).forEach(function(inputName,outputName){
var inputElement="#"+inputName;
var outputElement="#"+ioMap[inputName];
console.log(inputElement);
console.log(outputElement);
$(inputElement).keyup(function() {
$(outputElement).html($(this).val());
});
});
}
doTextBinding(myIOMap);
Replace your JavaScript with the following code, it will do the same without having to rewrite the key-up binding for each element. Make sure you call the function every time the page initializes though.