how to add enter key to calculate taxes? - javascript

id like to know how i can add onclick="calculer" to work with enter keyboard shortcut too. ive tried many code like this one
document.body.onkeydown = function(e) {
if (e.keyCode == 13)
validatePass();
};
but nothing seems to work. sorry im a begginer at school only beeing able to post was complicated to me :P would be much appreciated
<html>
<head>
<title>Page Title</title>
<meta charset="UTF-8" />
<script src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script>
function calculer() {
montant = Number(document.getElementById("montant").value);
taxe = (montant * 14.975) / 100;
total = (montant * 114.975) / 100;
ment.getElementById("taxe").value = taxe + " $";
ment.getElementById("total").value = total + " $";
}
</script>
</head>
<body>
Montant:
<br />
<input type="number" id="montant" />
<br /><br />
Taxe:
<br />
<input type="text" id="taxe" placeholder="$$$$$$$$$$$$$$$$$$$$$$" readonly />
<br /><br />
Résultat:
<br />
<input type="text" id="total" placeholder="$$$$$$$$$$$$$$$$$$$$$$" readonly />
<br /><br />
<button type="button" onclick="calculer()">Calculer</button>
</body>
</html>

const elementOne = document.getElementById('taxe');
const elementTwo = document.getElementById('taxe');
elementOne.addEventListener('keyup',(e) => {
if(e.keyCode == 13){
calculer()
//use the same process for elementTwo
}
})

You should attach the event listener to the document.
Here's how you can do it:
document.addEventListener("keyup", e => {
if (e.keyCode == 13) {
calculer();
}
});

Related

Empty input fields/values after form submit

I've got a very simple form and I'm want the values to empty when I submit in order to use again without refreshing the page. What I've got isn't working for some reason.
My initial idea was to set the values of the inputs to empty strings on form submit, but when I log them into the console they don't do that. Anyone know what I'm doing wrong here?
<!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>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
let form = document.getElementById("form");
let volume = document.getElementById("volume");
let denied = document.getElementById("denied");
let charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function (e) {
e.preventDefault();
volume = volume.value;
denied = denied.value;
charges = charges.value;
let curDenialRate = parseFloat((denied / volume) * 100);
charges = parseFloat(charges * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(charges);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
volume = " ";
denied = " ";
charges = " ";
return false;
};
Use HTMLFormElement.reset():
let form = document.getElementById("form");
const volume = document.getElementById("volume");
const denied = document.getElementById("denied");
const charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function(e) {
e.preventDefault();
let a = volume.value;
let b = denied.value;
let c = charges.value;
let curDenialRate = parseFloat((b / a) * 100);
c = parseFloat(c * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(c);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
form.reset();
return false;
};
<!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>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
How you are clearing values will not work. You are trying to change the variable but that will not affect the DOM element or its value.
You will have to use the below code with value property to change the value.
document.getElementById("volume").value= " ";
document.getElementById("denied").value= " ";
document.getElementById("charges").value= " ";

how to iterate through HTML elements and sum the values using for loop

i have an issue using for loop to sum the values through elements inside HTML by pressing button but the code did not work correctly also i tried to show alert a massage that says "not a number" but every time show the same massage once i press the button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="" placeholder="Enter a Number " >
<input class="inp" type="" placeholder="Enter elec" >
<input class="inp" type="" placeholder="Enter food " >
<input class="inp" type="" placeholder="Enter car " >
<input class="inp" type="" placeholder="Enter resturent " >
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script
const btn= document.querySelector('.btn')
const total = document.querySelector('.total')
const inp = document.querySelectorAll('.inp')
btn.addEventListener('click',function(){
if (isNaN(inp.value)) {
alert("Not a number")
console.log(inp.value);
} if (inp.value === ""){
alert("enter number ")
}
for (let i = 0; i <inp.length; i++) {
let index = 0
const current = index + inp[i].value
total.innerHTML = index
}
})
</script>
</body>
</html>
Change to input type=number. Also check with typeof if the variable is a number. If not, you can convert it with JavaScript function parseInt().
Please change the type of your inputs, then move your "validation" inside your loop, then
move your counter outside the loop and change it to "let", then cast to number the input value before sum into the current.
have a nice day
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="number" placeholder="Enter a Number ">
<input class="inp" type="number" placeholder="Enter elec">
<input class="inp" type="number" placeholder="Enter food ">
<input class="inp" type="number" placeholder="Enter car ">
<input class="inp" type="number" placeholder="Enter resturent ">
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', function () {
const total = document.querySelector('.total')
const inps = document.querySelectorAll('.inp')
let current = 0;
for (let i = 0; i < inps.length; i++) {
if (isNaN(inps[i].value)) {
alert("Not a number")
break;
} if (inps[i].value == "") {
alert("enter number ")
break;
}
current += +inps[i].value
total.innerHTML = current
}
})
</script>
</body>
</html>

Issue with confirmation window

Working on a HW project and I've followed it step by step to try and get this confirmation window to pop up but can't figure it out. I'm not getting any console errors so I assume my code is just broken somewhere.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<article>
<h2>Change of address form</h2>
<form>
<fieldset id="contactinfo">
<label for="addrinput">
Street Address
</label>
<input type="text" id="addrinput" name="Address" />
<label for="cityinput">
City
</label>
<input type="text" id="cityinput" name="City" />
<label for="stateinput">
State/Province
</label>
<input type="text" id="stateinput" name="State" />
<label for="zipinput">
Zip/Postal Code
</label>
<input type="number" id="zipinput" name="Zip" />
</fieldset>
<fieldset id="submitsection">
<input type="button" id="submit" value="Submit" />
</fieldset>
</form>
</article>
<script>
function processInput() {
var propertyWidth = 300;
var propertyHeight = 100;
var winLeft = ((screen.width - propertyWidth) / 2);
var winTop = ((screen.height - propertyHeight) / 2);
var winOptions = "width=300,height=100";
winOptions += ",left=" + winLeft;
winOptions += ",top=" + winTop;
window.open("confirm.htm", "confirm", winOptions);
}
function createEventListener() {
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput,
false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
}
if (window.addEventListner) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
</script>
</body>
</html>
Move this code outside of createEventListener:
if (window.addEventListner) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}

form validation dynamic created not working

I have some fields (created dynamically) in a page and I am trying to each element on form submit .Bellow code is sample ,only txtAge field validate, txtName not validating .Is there any option to validate each field with bellow code?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
function txtName_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
}
function txtAge_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
}
</script>
</head>
<body onload="txtName_FormValidation(); txtAge_FormValidation()">
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>
Why don't you do like this?
calling all validations from same function?
<script>
document.getElementById('entryForm').onsubmit = function(e){
txtName_FormValidation(e);
txtAge_FormValidation(e);
}
function txtName_FormValidation(e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
function txtAge_FormValidation(e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
</script>
You are replacing the first onsubmit event, for this reason only dispatch the second function.
You can try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('entryForm').onsubmit = function (e) {
e.preventDefault();
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
};
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
};
}
}, false);
</script>
</head>
<body >
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>

javascript function not calling possibly due to scope issue

I am looking to call my clear() JS function to clear the text values in some input fields on my webpage, but for some reason, the function doesn't appear to be called correctly. I believe this may be a scope issue, but I'm not sure.
Here is my markup, script and styling kept together for ease-of-use currently, but will be mended once scripting is finalized:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
}
function clear()
{
document.getElementById('variablea').value = "";
document.getElementById('variableb').value = "";
document.getElementById('variablec').value = "";
}
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button" onClick="calculateQuad()">
<input id="erase" value="Clear" type="button" onClick="clear()">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
You must rename the 'clear' method. Try naming it 'clearFields' or something. (;
Also, if you only want to reset the form fields you can also do this:
onClick="this.form.reset()"
You can avoid the issue with function naming entirely by using:
document.getElementById("calculate").onclick = function () {
...
};
document.getElementById("erase").onclick = function () {
...
};
This is actually a preferred method of adding event handlers by web developers because it avoids cluttering the HTML code with inline snippets of JavaScript while retaining cross-browser compatibility.

Categories