VAT Calculator using javascript - javascript

I want to create a VAT calculator where the user enters an amount and the amount is multiplied by 1.15 (assume VAT is 15%) and alert message displays the results. So if the user enters an amount of £500, then the alert message should display £575.
function mult(x) {
if (x.length == 0) {
alert("Numbers cannot be blank");
return;
}
if (isNaN(x)) {
alert("Value entered is not numeric");
return;
}
var result = parseInt(x) * 1.15;
alert("Multiplication: " + result);
}
<h1>VAT Calculator</h1><br> Amount(£): <input type="text" id="amount" name="txt_amount">
<br><br>
<button onclick="calculateVAT(amount.value)">Calculate Total Amount</button>
The code of for the javascript is not working.Can you please help me. Thanks.

The error is occurring because when the button is clicked, the code is looking for a function called calculateVAT() which does not exist in the JS.
To resolve the issue, either rename your function called mult() to calculateVAT() or change onClick in the button tag to call the mult() function rather then calculateVAT()
Calculate Total Amount

Rename your function from mult to function calculateVAT(x)
function calculateVAT(x) {
if (x.length == 0) {
alert("Numbers cannot be blank");
return;
}
if (isNaN(x)) {
alert("Value entered is not numeric");
return;
}
var result = parseInt(x) * 1.15;
alert("Multiplication: " + result);
}
<h1>VAT Calculator</h1><br> Amount(£): <input type="text" id="amount" name="txt_amount">
<br><br>
<button onclick="calculateVAT(amount.value)">Calculate Total Amount</button>

Related

Trying to create a random game but doesn't seem to work

Under my form action, I called the textbox and buttons. It was suppose for the user to key in 2 values one being the highest value and another being the lowest value, it will then generate a random value between the lowest and the highest. The user will than guess the number if its correct it will print out the message correct
<form action="random" method="get" onSubmit="return validate()">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<br/><span id="numbers1"></span>
<br/><input id="rand" type="submit" value="submit" onclick="Random()"><br/>
<input id="guess" type="text" value="Random Number Generator">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</form>
My script consist of the methods and functions to use, I think the problem lies at the RandomNumber() function, im not sure where did I go wrong, but please assist me
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
This is the function to generate a random number in between the lowest number and the highest number.
function Random()
{
var value1 = document.getElementById("digit").value;
var value2 = document.getElementById("digit1").value;
minvalue= Math.ceil(value1);
maxvalue= Math.floor(value2);
var random = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
document.getElementById("guess").value=random;
}
And this is the part where I assume it may have cause the entire program to stop working, its after I wrote down this codes and my web page doesn't perform the way I want it to be.
function RandomNumber()
{
var value3 = document.getElementById("digit").value;
var value4 = document.getElementById("digit1").value;
minvalue= Math.ceil(value3);
maxvalue= Math.floor(value4);
var random1 = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
var maxtries=5;
var counter=0;
var true=document.getElementById("textbox").value;
while(true!=random1)
{
document.getElementById("total").value=total;
counter +=1;
if(counter>maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
if(true==random1)
{
document.getElementById("correct").innerHTML="Correct"
}
}
}
When I look at your code I see a couple of red flags.
E.g. true is a reserved keywoard in JS, you can't assign a value to it:
var true=document.getElementById("textbox").value;
This must throw an error in your development console.
Also in your loop while(true!=random1) neither true or random1 are reassigned, so if true in the beginning, the condition will never become false, hence the loop is never left in this case!
In general you should try to narrow your issue down, look at the errors and rather ask for help on smaller snippets where you ask concrete questions. With a statement like my web page doesn't perform the way I want it to be it is hard to provide help.

Very new to Javascript. Can't seem to get 1 function to work in my code (berekenBedrag). Needs to calculate the total

I'm struggling with the same code for days now and it's becoming frustrating.
I checked youtube, google, read in Flanagan but I can't seem to find the answer.
Now, I believe I came to the end of my code but one function I don't get to work.
I need to have 1 input text were the user puts in an amount, presses enter and the total needs to go to input text 2.
After each input, the input from text 1 needs to get emptied.
Everything works except for calculating the total in input text 2.
Thanks for reading and appreciate the help.
This is my code:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="input1"><br><br>
<input type="text" id="input2">
<script>
document.getElementById("input1").addEventListener("keyup", function(e) {
if ( e.keyCode === 13) {
myFunction();
}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input1").value="";
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2) +
" euro";
}
function berekenBedrag(pBedrag) {
var input = document.getElementById("input2");
pBedrag = pBedrag+input;
//This function is wrong but I don't know how to calculate the total from input 1 and 2 together.
return pBedrag;
}
function leesInvoer(invoerId) {
var invoer = document.getElementById(invoerId);
var getal = +invoer.value;
return getal;
}
</script>
</body>
</html>
Put the " euro" outside the input
Parse the number
Disable the other field from accepting input
Use "change" in case they use another input method (tab off, hit "enter" or some other way (click off) etc.
Reset the input value where you got it (I used null but that is a style choice)
document.getElementById("input1")
.addEventListener("change", function(e) {
//if (e.keyCode === 13) {
myFunction();
//}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2);
}
function berekenBedrag(pBedrag) {
let input = document.getElementById("input2");
pBedrag = pBedrag + (input.value * 1);
return pBedrag;
}
function leesInvoer(invoerId) {
let invoer = document.getElementById(invoerId);
let getal = !isNaN(parseFloat(invoer.value)) && isFinite(invoer.value) ? parseFloat(invoer.value) : 0;
invoer.value = null;
return getal;
}
<div><input type="text" id="input1"></div>
<div>
<input type="text" id="input2" disabled><span> euro</span></div>
You can use a global variable to store the total (which starts at 0) and add the value of the input after converting to a number (using the unary plus operator) each time.
document.getElementById("input1").addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
myFunction();
}
});
let total = 0;
function myFunction() {
var bedrag = +document.getElementById("input1").value;
total += bedrag;
document.getElementById("input1").value = "";
document.getElementById("input2").value = total.toFixed(2) +
" euro";
}
<input type="text" id="input1"><br><br>
<input type="text" id="input2">

This will not return the "if" statement, even though terms are met

This code should detect where a number is above 1,000,000,000 and below 9,999,999,999. I try to input numbers between these 2 values, but it still returns the else statement. Where is the problem in this code?
<html>
<head>
<title>Checking with RegExp</title>
</head>
<body>
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
<script>
function checknumber() {
var tendigitnum = document.getElementById("inputnumber")
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
}
else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
</script>
</body>
</html>
You're comparing an HTML element to a number. You want to compare a number to a number, by:
Using the .value property on the element to get the string, and
Parsing that string to a number (you have lots of different ways to do this depending on your use case; see this answer for a list of them)
For instance:
var tendigitnum = Number(document.getElementById("inputnumber").value);
Live Example:
function checknumber() {
var tendigitnum = Number(document.getElementById("inputnumber").value)
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
} else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
On modern browsers you could use a number input:
<input type="number" id="inputnumber">
and use its valueAsNumber property instead of value, since valueAsNumber will already be a number. You can even add the range validation to the input. More on MDN.
You need to check the value in your element, in your code you are checking element

Javascript number guessing game - setting up the counter & while loop

I'm trying to create a random number guessing game in Javascript that compares user input to a number generated with the math.random method. I'm confused by how to set up the counter the right way. I have to validate the number, display each guess with "too high," "too low" or "you win" then show the 'secret' number at the end. Not sure what I'm doing wrong! Right now it is overwriting each answer and the counter is staying at #5.
function myFunction() {
var userInput = document.getElementById("text").value;
// test for valid input number from 1 to 999
if (userInput < 0 || userInput > 999) {
alert("Your number must be from 1 to 999");
} else {
alert("Input OK");
} // end function myFunction
var randomNum = Math.floor(Math.random()* 999)+1;
var userInput = document.getElementById("text").value;
var counter = 0;
var totalGuesses = 0;
while (totalGuesses <= 5) {
counter++;
document.getElementById('loopResults').innerHTML = "<p>You have made" + counter + "guesses</p>";
if (userInput < randomNum) {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too low!</p>";
} else {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too high!</p>";
}
}
}
</script>
</head>
<body>
<h1>Guessing Game</h1>
<p id="loopResults"></p>
<form action="" method="post" enctype="multipart/form-data" name="userData">
<input name="userInput" id="text" type="text" size="10" /> - Enter a number from 1-999!</form>
<p><span style="background-color:#066aff; color: #ffffff; padding: 5px;" onclick="myFunction();" >enter number</span>
</p>
</body>
You don't need a while loop here. What happen is simply once it enters the while loop, it increments your counter to 5.
Take the while loop out and it will do what you want it to do.
And I don't think you need the totalGuesses
Edit:
So I further look into your code. In order to do what you want it to do, instead of putting everything in your myFunction, here are the steps:
create a random_number
create a counter
a function that is bind to onclick, this is where the main logic is. And here's what you need to do.
get the input result from the input field, and parse it to Integer
compare with the stored random_number
if correct, alert ok
if not, increment the counter
if the counter reaches limit, alert and show result
Not going to write down the code, and I think you can figure it out.

validate field length

i want my roll number length should be equl to 4 and the data inserted can only be integer..
how can it be possible through java script
i am trying this code but it is just checking it, if roll number is greater then 4 it displays error but also insert the roll number
function rollnumber(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert(" nter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
rollnumber(document.getElementById('rollnumber'), 1, 4);
return true;
It confuses the javascript rollnumber is both a function name and an element id.
The function needs to be executed on a form when it submits otherwise it will continue submitting instead of stopping
Here is the fixed code. Tested.
<form onsubmit="e_rollnumber()">
<input type="text" id="rollnumber" />
<input type="submit" value="Click here to roll the number" />
</form>
<script type="text/javascript">
function e_rollnumber(){
var len = {min:1,max:4};
var input = document.getElementById('rollnumber');
if(input.value.length>=len.min && input.value.length<=len.max) return true;
alert("Please enter between " +len.min+ " and " +len.max+ " characters");
input.focus();
return false;
};
</script>

Categories

Resources