Why won't my alert work in one of my functions? - javascript

I want the nameVerification() function to throw the alert() message when the user hits submit. For example, if the user enters something like 45 in the name field, I want that alert in nameVerification() function to be called. Right now, when the user does type in a number in the name field, the alert() in the formSubmission() function is being called.
Side note:
formSubmissionfunction works perfectly. In other words, if the user enters a number < 13 in the age field, the functions alert() gets called normally with no problems. If the user enters a number > 13, it works, also, without a problem. Just thought I'd let you guys know that too.
signUp.html
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script type="text/javascript" src="signUp.js"></script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="signUp.css">
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div class="moveUsername">
<label for="usr">Name:</label>
<input type="field" class="form-control" id="nameVerify" placeholder="Username" required="required">
</div>
<div class="ageMovement">
<label for="usr" >Age (Must be 13 years or older to play):</label>
<input type="field" class="form-control" id="ageVerify" name="ageChecker" placeholder="Age" required="required">
</div>
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
</form>
</body>
</html>
signUp.js
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if(typeof name !== 'string') {
alert("That's not a name!");
}
}
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}

age is also a string in this function:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
If you want to do a numeric compare, you need to parse first:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if (age) {
var ageInteger = parseInt(age, 10);
if (ageInteger < 13) {
alert("You're too young, you can't play the game");
}
}
}

You have two onclick attributes on the button
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
You can only have one

Your typeof test is failing because the value returned from a text input is always of type string. You can test to see if a provided text value is numeric with the following function:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The real answer, however, is that you'll need to improve your input validation tests to determine what you want, rather than test for all the things you don't want. For example, testing for a numeric value as above would not work if someone entered "t#^!" in the field, which is likely not a value you would want in a name field. This is where regular expressions, and the built-in validations from HTML5 fields can help.

You can change your nameVerification function as follows:
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if (name) {
var num = parseInt(name) || -1;
if (num >= 0 && num < 13) {
alert("That's not a name!");
}
}
}
and change your onclick values in the html to be:
onclick="formSubmission();nameVerification()"

it's because the javascript is not loaded yet.
Move:
<script type="text/javascript" src="signUp.js"></script>
To just above the </body> tag.

You should use parseInt:
var age = parseInt(document.getElementById("ageVerify").value);

Related

Javascript help needed for simple form validation

I am currently trying to create a very simple validation script with JS. Basically, I want a alert to come up if the text inputted into a form is shorter than 5 characters, or longer than 25.
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate()
{
var yourpw = document.forms.passwordform.yourpassword.length;
if (yourpw < 5);
{
alert("password is too short");
return false;
}
if (yourpw > 25)
{
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate();">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
I am not sure what exactly I am missing or why it wont work but the goal of what i want is that when text is inputted into the text box named "yourpassword", a script will run that will show a message if either one of these conditions are met: shorter than 5 characters, or longer than 25, warning the person typing that their password does not follow the guidelines, if the password meets the guidelines, then i just want a simple confirmation message to appear. Anyways i appreciate any help as this is frustrating me and making me want to give up learning JS. Thanks
you need to first prevent the default behavour of form submit .
use
function validate(e)
{
e.preventDefault();
var yourpw = document.forms.passwordform.yourpassword.value.length;
... rest of code
}
Try updating your validate function to as follows:
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5) {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
You need to grab the input fields value, as mentioned, the input field does not have a length (#Xufox) as well as prevent the default behavior for form submission.
Edit:
Full working example:
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5); {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate(event);">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
Use this : but give id name yourpassword to input field .. So you can take the value easily
var yourpw = document.getElementById("yourpassword").value;
var len = yourpw.length;
If ( len < 5 )
{
alert ("this is short");
}
elseif(len>25)
{
alert(" too long")
}
else
{
//// your code
}
You can easily validate forms via RegExp.
use this function for validate 5 character limit.
var pw = document.getElementById("yourpassword").value;
function isValidatePW(PW){
var pwRegExp - /\d{5}/
return pwRegExp.test(PW);
}

Do nothing if an input field is empty and if it has a value check to see if it is numeric and display an alert if it is not

I am trying to make a form that automatically sums input fields on blur and displays the sum in an inactive "Total:" field. I don't want to run anything if a user puts focus in an input then moves focus away without inputting anything and if a user does input something I want to restrict the field to only numbers. If there is a better way of doing this, please let me know. Here is an example of my current approach:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Calc</title>
<script src="javascript.js"></script>
</head>
<body>
<h1>Sales By Month</h1>
<form method="get">
<label for="january">January:</label>
<input type="text" id="january" class="amount" onblur="isNum(); calculateSum();">
<label for="february">February:</label>
<input type="text" id="february" class="amount" onblur="isNum(); calculateSum();">
<label for="total">Total:</label>
<input type="text" id="total" disabled>
</form>
</body>
</html>
JavaScript
function calculateSum() {
var elems = document.getElementsByClassName('amount');
var myLength = elems.length;
sum = 0;
for (var i = 0; i < myLength; ++i) {
sum += elems[i].value *1;
}
document.getElementById('total').value = sum;
}
function isNum() {
var amounts = parseInt(document.getElementsByClassName('amount').value);
if (isNaN(amounts) == true && amounts != '') {
alert("Please enter a numeric value");
}
}
The calculation function currently works but the "Please enter a numeric value" alert pops up every time I tab away from a field regardless of the contents.
First you need to test the value of the element that losts focus, which means you should pass it in the argument like this
onblur="isNum(this); calculateSum();"
then in your isNum function in javascript remove document.getElementsByClassName and use the argument instead ... and don't test if amounts != '' because it will never be equal to empty string while you do this amounts = parseInt(elem.value); you have to test on the elem.value
function isNum(elem)
{
var amounts = parseInt(elem.value);
if (isNaN(amounts) == true && elem.value != '') {
alert("Please enter a numeric value");
}
Here is a jsFiddle

set of passwords in arrays, the user only has 3 chances

I need to make an array of passwords looping for the user to be redirected to another site. After 3 mistakes the user cannot try again. This is what I have so far, but it doesn't work.
<form>
<label>Please enter Password</label>
<input type="text" id="Pass" />
<input type="button" value="go" onClick="check()" />
</form>
<script type="text/javascript">
function check()
{
var password = ["123","456","789"]
for(a=0;a=password.length;a++)
{
if (user="password")
{
document.location.href="http://yahoo.com";
}
else
{
alert("wrong password");
}
}
}
</script>
As you are calling a function check from the onclick event, you need a function by that name in your code.
When calling the check function you can pass along the value from the text box, so that the function can use it to check against the items in the array.
In your code the condition for the loop is wrong. Using a=password.length means that the loop won't run at all. The loop runs as long as the condition is true, it's not used to mark the end of the loop.
Use the == operator to check if two values are equal (the = operator is for assignment). Use password[a] to get the item from the array which has the index from the variable a.
In the loop you should only check for when the strings are equal. If you have an else case there, it will tell you that the password is wrong for every password that didn't match. Use return to exit from the function when you have set the location.
After the loop you know that none of the password matches, so then you know that the password was wrong.
<body>
<form>
<label>Please enter Password</label>
<input type="text" name="Pass" />
<input type="button" value="go" onclick="check(this.form.Pass.value)"/>
</form>
<script type="text/javascript">
var password = ["123","456","789"];
function check(pass) {
for(a = 0; a < password.length; a++) {
if (pass == password[a]) {
document.location.href="http://yahoo.com";
return;
}
}
alert("wrong password");
}
</script>
</body>

Clearing the field of a form with a button

Sounds easy probably, but not for a beginner programmer :)
I have a simple 3 field form with a submit button and a clear button. This is for a homework assignment, and we have been tasked to get the "Clear Fields" button to work properly. Here are more specific instructions:
"Add the JavaScript code for an anonymous function that's stored in a variable named clear. The function should clear the text boxes by using the $ function to get a Textbox object for each text box and then setting the value property of the textbox to an empty string. Then, add a statement in the onload event handler that attaches the clear function to the click event of the Clear Entries button."
I was able to add the statement to the onload event handler:
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
But it is the other part I am having problems with.
Add the JavaScript code for an anonymous function that's stored in a variable named clear:
var clear = function () {
Object.Method
}
Here is my full code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
var clear = function () {
miles.Text = String.Empty
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label> </label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
And here is the code we were supplied with to work off of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</section>
</body>
</html>
You've got several issues going on:
You're mixing Javascript and jQuery in ways that don't quite work.
jQuery's methods and objects work differently than "pure"
Javascript, so be mindful of that.
The window.onload doesn't work the way you've got it. To be
consistent, do it the jQuery way with a $(document).ready() method
instead.
You're missing the # indicator on your jQuery IDs. This is
imperative or it won't find the ID of the elements you're calling.
It looks like you're mixing VB/C# code in with your javascript, such
as the String.Empty call, etc. Those objects/methods work from the
server and not in Javascript, so that's another issue (it's been a
while since I've worked in C#, so double check me on that).
Here's my solution below. I tweaked a few things to help with what I think you're going for (such as clearing ALL fields with the "Clear" button instead of just the miles field).
I understand you're a student, so don't make it a habit of coming here and trying to find people to do your homework for you. You did provide an attempt at some code, and there were a number of issues in it, so I chose to rectify them for you and explain the reasons since there were so many. Others are not as generous, but I was a struggling student once, too, so I get it when you're banging your head against the wall. :-)
$( document ).ready( function () {
var clear = function () {
miles.value = "";
gallons.value = "";
mpg.value = "";
}
var calculateMpg = function () {
var miles = parseFloat($("#miles").val());
var gallons = parseFloat($("#gallons").val());
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");
}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");
}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");
}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("#mpg").val(mpg.toFixed(1));
}
}
$("#calculate").bind("click", calculateMpg);
$("#miles").focus();
$("#clear").bind("click", clear);
});

default value of textbox not changed after typing different value to it

I assigned default value to textbox after the value passed by query string from
previos web page.
it looks like that:
<form method="post" name="create" onsubmit="return checkPercentValue()" style="font-size: medium; margin-top: 10%" dir="rtl" >
<input type="text" size="5px" id="stocksPercents" name="stocksPercents" value="#stocks">
</form>
Now when the user typing another value to the textbox for change the default one,
I call for javascript function to validate the value in some range (0 - 100).
the function:
<script type="text/javascript">
function checkPercentValue() {
var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));
if (value > 100 || value < 0) {
window.alert("please insert value between 0 - 100");
return false;
}
else {
return true;
}
}
</script>
So I checked why when I put value for example: 200 (greater then 100), the alert doesn't pop up(!!!)
I added to the code this line:
document.write(value);
And I saw the value allways stay the default one....and will not changed even I changed it in the
textbox before.
So I guess the problem is that typing value into the textbox can't change the default value
just like that...
what the solution to that?
thanks...
Replace this
var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));
With
var value = parseInt(document.getElementById("stocksPercents").value);
This will fix your problem.
You might also want to consider using jQuery. The syntax is easier, much shorter to type, and cross-browser compatible (that is, you don't need to worry about this b/c jQuery guarantees that for you.)
Here is your code in jQuery:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function checkPercentValue() {
var value = parseInt($("#stocksPercents").val());
if (value > 100 || value < 0) {
alert('I am GREATER');
window.alert("please insert value between 0 - 100");
return false;
}
else {
alert('I am LESS');
return true;
}
}
$(document).ready(function() {
$('#stocksPercents').blur(function() {
checkPercentValue();
// alert('Yo!');
});
});
</script>
</head>
<body>
<form method="post" name="create" onsubmit="return checkPercentValue()" dir="rtl" >
<input type="text" size="5px" id="stocksPercents" name="stocksPercents" value="#stocks">
</form>
</body></html>

Categories

Resources