JS Calculation assistance - javascript

I'm having some issues with my code, I'm creating a site to get it to calculate mortgages with down payments of:
3% of the first $25,000
Insures home mortgages requiring a down payment as follows:
3% of the first $25,000
5% of the remainder
The input consists of a SSN and a mortgage amount. I wanted it to print the applicant’s SSN and the amount of down payment required. Reject any applications over $70,000. Don’t forget to validate your input. If the input is not good, and I want it to display an error message and ask for the input data again.
<html>
<head>
<title>Mortgage Charges</title>
<script type="text/javascript">
// Program name: FHA
// Purpose: print the applicant’s SSN and the amount of down payment required
// Date last modified: 3/29/12
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
var mortgage = 0;
if (mortgage <= 25000) {
amtOwed = 0;
}
else if (mortgage >= 5%) {
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
window.onload = function() {
document.frmOne.onsubmit = function(e) {
mortgage();
return false;
};
};
</script>
</head>
<body>
<form name="frmOne">
Enter your SSN:<input type="text" id="ssn" /><br />
Mortgage amount:<input type="text" id="mortage" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

I'm afraid I can't fathom your logic. How do you expect this to work?
Let me break down what your current code does:
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
// Get the value from the text box, and convert it to a number. That's good.
var mortgage = 0;
// Initialise a variable. Fair enough.
if (mortgage <= 25000) {
// You JUST set morgage=0. How can it be anything but less than 25k?
amtOwed = 0;
// You are overwriting the value you got from the form with 0
}
else if (mortgage >= 5%) {
// Okay, first of all this else will never be reached, see comment above.
// Second... 5% of what, exactly? If you want 5% of a number, multiply the number by 0.05
// Third, what's the point of this block if there's no code in it?
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
Basically, your code can be simplified to:
function morgage() {document.frmOne.mortage.value = 0;}
Because that's all it does.
I don't really understand exactly what you're doing, but hopefully explaining what your current attempt is doing will help you to find the answer.

Related

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

JavaScript code does not work as expected

So I made this little thing as I am quite new to programming, but when I open it in Chrome, I am able to type input but then nothing happens. Does anyone know how I can fix this code?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input type="submit" value="GO!">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low +1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
for (var i=0;i=0) {
if (guess>number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
}
if (guess<number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
}
if (guess==number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
}
}
}
startGame();
</script>
</body>
</html>
You've got a lot of problems, starting with a syntax error.
You have a submit button, but no form to submit. You really just need a button. But, even then, you have to set up a click event handler for it.
Then, your loop isn't configured properly.
You also are not accessing the data the user has typed into the textbox correctly - you need to get the value of the element.
Your if statements should be else if.
The b element should not be used just for presentation. HTML is a "semantic" language, meaning that you use a tag to describe the meaning (not presentation) of an element. For styling use CSS.
See comments inline below for details.
/* CSS is for presentation, not HTML */
#bold { font-weight:bold; }
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<!-- Don't use HTML for styling, use it for semantics. -->
<span id="bold">Guess:</span> <input type="text" id="guess">
<!-- You need a <form> if you have a submit button. For this, you just want a button. -->
<input type="button" value="GO!" id="go">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
// Get a reference to the output area just once
var output = document.getElementById("bold");
// Give the user 3 tries. Your loop wasn't configured properly.
for (var i=0; i < 3; i++) {
// You want to access the data in the textbox. That's the value
// Also, if the first condition isn't true, try the next and so on.
// This is done with else if branches
if (guess.value > number) {
output.textContent = "You're too high, try lower!";
} else if (guess.value < number) {
output.textContent = "You're too low, try higher!";
} else if (guess.value == number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
break; // Get out of the loop because the game is over.
}
}
}
// Set it up so that clicks on the button run the function
document.getElementById("go").addEventListener("click", startGame);
</script>
</body>
</html>
you have some errors:
this doesnt work, it wont loop. actually, why do you want to loop?
for (var i=0;i=0) {
this will run the function once, this means when the user writes the value it wont be checked
startGame();
the button doesnt do anything, also it has a submit and you don't have any forms:
input type="submit" value="GO!">
on each if, the conditions are exclusive, use if/else
below is a working code:
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input value="GO!" onclick="checkGuess()">
<script>
var number = 0;
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
number = getRandomNumber(1, 10);
}
function checkGuess() {
var guess = document.getElementById("guess").value;
if (guess > number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
} else if (guess < number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
} else if (guess == number) {
alert("You're correct, the number is " + number + "!!!");
alert("Thanks for playing my game and have a good day!");
}
}
startGame();
</script>
</body>
</html>
Although i have no idea about what your program does. you have a syntax error at
for (var i=0;i=0) {
and also you should bind an event to that button rather than doing a submit.

Troubleshooting JS conditional

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when clicked changes the amount to $5. I'm trying to get get it so that if say the user tries to enter a number such as 10, 15 or 20 as examples it will allow them to type it. Currently it is converting anything less than 5 for the starting number to 5 which makes it impossible.
$("#donrAmountInput").on("input", function() {
setDonrAmount("Other");
});
function setDonrAmount(id) {
var amt;
$('#donrAmountButtons .active').removeClass('active');
if (id == "Other") {
amt = $("#donrAmountInput").val() > 5 ? $("#donrAmountInput").val() : 5;
$('#otherAmount button').addClass('active');
}
else {
amt = id.substring(10);
$('#donrAmount' + amt).addClass('active');
}
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
You can set your input type to number specify min,max,required attributes and then check the validity of it via javascript/jQuery.
function myFunction() {
var inpObj = $("#id1")[0];
if (inpObj.checkValidity() === false) {
$("#demo").html(inpObj.validationMessage);
} else {
$("#demo").html(inpObj.value);
}
}
$('button').on('click',function(){
myFunction();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" type="number" min="5" max="300" required>
<button>OK</button>
<p id="demo"></p>

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.

how to show text typed in a password input type otherwise hide the password

I want to allow users to see what they type in a password field. For instance, as soon as they type a letter in the field, they should see what was typed and the letter should change back to its default bullet.
This jQuery plugin does what you want: https://code.google.com/archive/p/dpassword/
The blog post contains the details.
Another option is to swap the type of the field using a checkbox ("Show password?"). Switching the type of the input element between text and password should achieve this. If that doesn't work, you need to create a new input element and copy the value.
Note on security: The password is hidden for a reason. Just to give you an idea of the possible attacks, here is the ones I know of:
If a smart phone is lying on the table next to your keyboard, then the vibrations caused by typing can be recorded and the keys you pressed can be calculated from that.
If the monitor is visible from outside the building, a good telescope can read you screen over quite a distance. If you wear glasses or there is a teapot, you can still read that at 30m.
So be aware that displaying a password does compromise security.
Related articles:
I Spy Your PC: Researchers Find New Ways to Steal Data
http://css-tricks.com/better-password-inputs-iphone-style/
Building uppon #SubhamBaranwal's answer that has the major drawback of losing the password field's value, you could do something like the following:
$(_e => {
const frm = $('#my-form');
const passField = frm.find('.pass');
const passCopy = $('<input type="hidden" />');
passCopy.prop('name', passField.prop('name'));
passField.prop('name', null);
passField.prop('type', 'text');
frm.append(passCopy);
let timer;
passField.on("keyup", function(e) {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
timer = setTimeout(function() {
copyPass();
passField.val(createBullets(passField.val().length));
}, 200);
});
function createBullets(n) {
let bullets = "";
for (let i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
function copyPass() {
const oPass = passCopy.val();
const nPass = passField.val();
if (nPass.length < oPass.length) {
passCopy.val(oPass.substr(0, nPass.length));
} else if (nPass.length > oPass.length) {
passCopy.val(oPass + nPass.substr(oPass.length));
}
}
/* for testing */
frm.append('<input type="submit" value="Check value" />');
frm.on('submit', e => {
e.preventDefault();
copyPass();
alert(passCopy.val() || "No Value !");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<input class="pass" type="password" name="pass" />
</form>
However, this remains a simplistic implementation that will only support editing the password from the end (appending characters or backspaces). For a full implementation, you'd have to check and record where the current selection lies at each keyUp, and then modify the recorded value according to what you get after the input field was updated. Far more complicated
I think you want something like this JSFiddle
HTML Code -
<input class="pass" type="password" name="pass" />
JS Code -
function createBullets(n) {
var bullets = "";
for (var i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
$(document).ready(function() {
var timer = "";
$(".pass").attr("type", "text").removeAttr("name");
$("body").on("keyup", ".pass", function(e) {
clearTimeout(timer);
timer = setTimeout(function() {
$(".pass").val(createBullets($(".pass").val().length));
}, 200);
});
});

Categories

Resources