I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.
Related
I'm a beginner in javascript. I ask a question on how to store the even numbers and display all the input even numbers into a <p> tag. For example, I input 4 so that the <p> displays 4. Then if I input again for example 6 so that <p> will become 4,6.
Is it possible to do it?
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
var numbers=[];
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
Your problem is that you are re-initialising your numbers array in every call to the number function. You can fix that by making it a property of the function and only initialising it if it is undefined. Then you can use join to convert the array into a comma separated list (although this is not strictly necessary as array to string conversion will do that for you anyway):
function number() {
this.numbers = this.numbers || [];
var number = document.getElementById("number").value;
if (number % 2 === 0) {
// alert("Your number is Even");
numbers.push(number);
document.getElementById("display_even").innerHTML = numbers.join(',');
}
else {
alert("Please Insert Even number");
}
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
It is a very simple thing. Each time when a user is entering a number and running the function, the number of values inside the array is set to 0. The simplest solution is to declare the array outside of the function:
var numbers=[];
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
var num = document.getElementById("display_even").textContent;
var numbers=[];
if(num){
numbers.push(num);
}
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
I am fairly new to javascript. Building a custom javascript calculator to set pricing for some products. There is sometimes a fee that is added. This fee is either a percentage of cost or an actual dollar amount. If it is a percentage, it will have a percentage sign. After researching, came up with the following solution that works only if a dollar amount is entered but not if percentage is entered. Is there a better solution?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
Because you are converting the input to a number with:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
Any symbols will cause that conversion to fail and therefore you wouldn't be able to perform your test.
var num = Number("234.50%");
console.log(num); // Not a Number
Instead, before doing the conversion, just simply test for the presence of the symbol with .indexOf which returns -1 when the test can't find a match.
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<input type="text" id="num1">
Having said all of that, I agree with the comments that a better way to handle this is by not asking the user to input the unit at all and just provide radio buttons:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>
I am trying to make a simple webpage where the user enters in a number and the page tells the user whether the number they entered in is even or odd. I would like to display that in the textbox at the bottom of the screen.
However, when I click the button, nothing happens. I even tried to add an "alert" when the button is pressed, but even that doesn't happen. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = number.value;
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
Take a look at these three lines here:
var userInput = document.getElementById('number');
var number = number.value;
alert(number);
You've retrieved a reference to the #number element and stored it in the userInput variable. Then, you've created a variable called "number," but the value you assigned to it is a property of the variable you just created.
However, this object reference stored in the number variable doesn't have this property, which is causing a runtime error. Try pressing F12 while in your browser with this script running and see what errors appear in the console.
Instead, try this out and see what reaction you get:
var userInput = document.getElementById('number');
var number = userInput.value;
number = parseInt(number);
I see a couple typos in your code, here's a modified version that I think ought to work:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = userInput.value; // you originally had "number.value", but that doesn't make any sense.
number = parseInt(number); // number is initialy a string, we need to convert it to an integer
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
You've made a mistake.
You wrote:
var number = number.value;
You should have written:
var number = userInput.value;
This is my function
function doMath() {
var counter; var nvalue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nvalue*price);
document.getElementById("total").value=amount ;
}
My html
<input type="" name="message" id="message" onkeyup="doMath()"maxlength="60">message
<input type="text" name="total" id="total" maxlength="60"> amount
when user enter value into message field it should calculate the amount automatically and show it in amount field.
but while i entering the value it show NAN
its not calculating can anyone help me how to fix this .i m new to javascript
You declared your variable as nvalue but used nValue instead.
function doMath() {
var nValue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nValue*price);
document.getElementById("total").value=amount ;
}
Your error is here:
amount = (nvalue * price);
It should be:
amount = (nValue * price);