onSubmit Function not able to call a function inside of it - javascript

I am trying to make a form. I want it to check the radio buttons to see if they have been clicked, and if not to have a message to the user to check one.
I tried to just enter it, then I tried to continue my else if statements with it (got error messages), then I tried making a function within the onsubmit function (it simply didn't initiate), then I tried making a function outside of the onsubmit function and am trying to call it, but it does not initiate. I've even tried moving the functions on top or below the onsubmit function.
I made the submitYesCancel to see if the problem was with the radioB function, but neither function will initiate.
I'm hopelessly stuck. Please help.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
/* <![CDATA[ */
function confirmPassword()
{
if (document.forms[0].password_confirm.value != document.forms[0].password.value)
{
window.alert("You did not enter the same password!");
document.forms[0].password.focus();
}
}
function submitForm()
{
submitYesCancel();
if (document.forms[0].name.value == ""
|| document.forms[0].name.value == "Your Name")
{
window.alert("You must enter your name.");
return false;
}
else if (document.forms[0].emailAddress.value == ""
|| document.forms[0].emailAddress.value == "Your Email")
{
window.alert("You must enter your email address.");
return false;
}
else if (document.forms[0].password.value == ""
|| document.forms[0].password_confirm.value == "")
{
window.alert("You must enter a password.");
return false;
}
else if (document.forms[0].sq.value ==""
|| document.forms[0].sq.value == "Your Security Answer")
{
window.alert("You must enter a security answer.");
return false;
}
radioB();
return true;
}
function submitYesCancel()
{
var submitForm = window.confirm("Are you sure you want to submit the form?");
if (submitForm == true)
{
return true;
return false;
}
}
function radioB()
{
var radioButton = false;
for (var i = 0; i < 4; ++i)
{
if (document.forms[0].special_offers[i].checked == true)
{
radioButton = true;
break;
}
}
if (radioButton != true)
{
window.alert("You must select a radio button.");
return false;
}
}
function confirmReset()
{
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<form>
<h2>Personal Information</h2>
<p>Name:<br />
<input type = "text" name = "name" placeholder = "Your Name" size = "50"/></p>
<p>Email Address:<br />
<input type = "text" name = "emailAddress" placeholder = "Your Email" size= "50" /></p>
<h2>Security Information</h2>
<p>Please enter a password of 8 characters or less: <br />
<input type = "password" name = "password" maxlength = "8" /></p>
<p>Confirm password<br />
<input type = "password" name = "password_confirm" size = "50" onblur = "confirmPassword();" /></p>
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "mother">What is your Mother's maiden name?</option>
<option value = "pet">What is the name of your pet?</option>
<option value = "color">What is your favorite color?</option>
</select></p>
<p><input type = "text" name = "sq" placeholder = "Your Security Answer" size = "50" /></p>
<h2>Preferences</h2>
<p>Would you like special offers sent to your email address?<br />
<input type = "radio" name = "radioButton" value = "Yes" />Yes<br />
<input type = "radio" name = "radioButton" value = "No" />No<br /></p>
<p>Are you interested in special offers from: <br />
<input type = "checkbox" name = "sCheckboxes" value = "e" />Entertainment<br />
<input type = "checkbox" name = "sCheckboxes" value = "b" />Business<br />
<input type = "checkbox" name = "sCheckboxes" value = "s" />Shopping<br /></p>
<button onclick="return submitForm();">Submit</button>
<button onclick="return confirmReset();">Reset</button>
</form>
</body>
</html>

The reason that it does not work because your Javascript is completely wrong.
}
radioB();
else // <--- what does it mean?
return true;
And
else if (radioButton ! = true) {
// <-- you have else if, but there is no if block and it is != not ! =
Next time when your Javascript does not work, try to see the error first. You can easily do this in Google Chrome. Hit Ctrl + Shift + J, go to Console tab. Then, fix each error when you encounter it until there is no more error.

Related

Why Javascript window.location can't redirect page if condition is true?

Im just started with javascript and this is for testing.
I have basic login form with username and password, and added some Javascript to pickup username and password values, check them and if its true should redirect me to another html page.
In this case Im used window.location..
Here is the code
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
window.alert ("Ne valja");
return false;
}
else if (password.length < 6) {
window.alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return true;
}
}
<form name = "login">
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="Validate();">Submit</button>
</form>
Here's a working fiddle:
http://jsfiddle.net/uLbycrhm/1/
I wouldn't recommend using window.location instead of the proper location.href, and I wouldn't recommend using window.alert instead of alert either (what's the difference?), so I've adjusted that as well. Using return here is unnecessary as well, because your function's tied to an onclick, not an onsubmit.
It's important to know that location is kind of an object, here is a link for your reference: MDN.
you can call function with return keyword
<script>
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
alert ("Ne valja");
return false;
}
else if (password.length < 6) {
alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return false;
}
}
</script>
<form name = "login" method="REQUEST" action=>
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="return Validate();">Submit</button>
</form>

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Password Validation javascript

I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?
Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>
Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}

Why does this xhtml file display JS code but doesn't run the function

Every time I try to run this xhtml file, it only displays the javascript file, it does not run the function. What am I doing wrong? Why the function does not run? I'm fairly new to JS and xhtml so any and all help is welcomed and appreciated. Here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--Submit form, Assignment 2-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<script type = "text/javaScript" src = "mss58.js"></script>
<title> Submit Form Assignment </title>
<meta charset="UTF-8">
</head>
<body>
<h1>Please Fill out the following Form</h1>
<form name ="SubmitForm" action = "mss58.js" onsubmit = "validate()" method="run">
Name: <input type ="text" name="firstname"><br />
Email address: <input type = "text" name="emailaddress"><br />
Password: <input type = "password" name = "pwd"><br />
Confirm Password: <input type = "password" name = "cpwd"><br />
Gender: <input type = "radio" name = "gender" value = "male">Male
<input type = "radio" name = "gender" value = "female">Female<br />
<br />
Comments: <br />
<textarea rows ="10" cols = "50"></textarea><br />
<input type = "submit" value = "Submit">
</form>
</body>
</html>
EDIT: I got the form to submit correctly however my javascript file does not want to check. I'm guessing my if statements aren't work. Can someone give it a once over and tell me why, when I type in an invalid password, username, or email that no alerts pop up? I'm sure it's something obvious, I've just never used javascript before this class
function validate(){
var name = document.forms["SubmitForm"]["firstname"].value;
var email = document.forms["SubmitForm"]["emailaddress"].value;
var password = document.forms["SubmitForm"]["pwd"].value;
var cpass = document.forms["SubmitForm"]["cpwd"].value;
var arrloc = email.indexOf("#");
var perloc = email.lastIndexOf(".");
var alph = false;
var num = false;
var sym = false;
if(name == null || name == ""){
alert("You must fill out the Name field");
return false;
}
if(arrloc < 1 || perloc < arrloc + 2 || perloc + 2 >= email.length){
alert("Email is not valid");
return false;
}
for(var i = 0, i < password.length-1, i++){
if(password.substring(i,i+1) == /[a-z]/){
alph = true;
}
if(password.substring(i,i+1) == /[A-Z]/){
alph = true;
}
if(password.substring(i,i+1) == /[0-9]/){
num = true;
}
if(password.substring(i,i+1) == /[^\w+$]/){
sym = true;
}
}
if(alph == true && num == true && sym == true){
return true;
}else{
alert("Your password is invalid!");
return false;
}
if(password == cpass){
return true;
}else{
alert("Your passwords do not match!");
return false;
}
};
validate();
You should include your javascript code into <script> tag.
In order to run the defined function, you've to call it, for example, like this: validate()
You need to change
<form name ="SubmitForm" action = "mss58.js" onsubmit = "validate()" method="run">
to
<form name ="SubmitForm" action = "TARGET_PAGE.php" onsubmit = "return validate()" method="POST">
In your JavaScript validate function, it should return false when the data is incorrect and return true otherwise.

How do I disable form dropdown option using javascript

I'm trying to disable the "name" text field in the form when "Choose" is selected in the drop down after the page loads (it's disabled when the page loads) ie after I've chosen one of the other two options that disable or enable that field, when I return to "Choose" i'd like the same field to disable. I can't see why the javascript I've written would prevent this from happening. Thanks!
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value === defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value === "") {
thisfield.value = defaulttext;
}
}
function checkPickup() {
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
/* Reset form values */
form.name.value = "His/her name";
}
}
</script>
<script type="text/javascript">
function validate(form) {
var errmsg = "Oops, you're required to complete the following fields! \n";
// Various other form validations here
// Validate "Pickup"
if (form.os0.value === "") {
errmsg = errmsg + " - Choose pickup or delivery\n";
}
// Validate "phone"
if (form.phone.value === "" || form.phone.value === "Mobile's best!") {
errmsg = errmsg + " - Your phone number\n";
}
if (form.os0.value != "Pickup from Toowong, Brisbane") {
// Validate "name"
if (form.name.value === "" || form.name.value === "His/her name") {
errmsg = errmsg + " - His/her name\n";
}
}
// Alert if fields are empty and cancel form submit
if (errmsg === "Oops, you're required to complete the following fields! \n") {
form.submit();
} else {
alert(errmsg);
return false;
}
}
</script>
</head>
<body>
<form name="form" action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return validate(form)">
<p class="row">
<input type="hidden" name="on0" value="Pickup and delivery" />Pickup and delivery<br />
<select name="os0" onchange="checkPickup()">
<option value="" selected >Choose</option>
<option value="Pickup from Toowong, Brisbane">Pickup from Toowong, Brisbane $1.00 AUD</option>
<option value="Brisbane +$23.60">Brisbane +$23.60 =$1.00 AUD</option>
</select>
</p>
<p class="row">Your daytime phone number<br />
<input type="text" name="phone" value="Mobile's best!" onclick="clickclear(this, 'Mobile\'s best!')" onblur="clickrecall(this,'Mobile\'s best!')" />
</p>
<p class="row">Recipient's name<br />
<input style="color: #ccc" class="name" type="text" name="name" value="His/her name" onclick="clickclear(this, 'His/her name')" onblur="clickrecall(this,'His/her name')" disabled />
</p>
<input name="custom" type="hidden" />
<input type="hidden" name="currency_code" value="AUD" />
<input class="button" type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1"> -->
</form>
</body>
</html>
This may be a simple misunderstanding of what you've written:
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
translates to the following in plain english:
If the value is NOT "Pickup from Toowong, Brisbane", enable the field, otherwise disable it.
which is equivalent to:
ONLY disable the field when the value is "Pickup from Toowong, Brisbane".
I believe the logic you're looking for is:
if (form.os0.value == "Brisbane +$23.60" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
though it might be prettier to code this with a switch statement due to the involvement of specific cases.
See DEMO
did you intend to type double equal to (==) or is the triple equal to (===) a typo in the question? Based on looking at your code, it looks to me like you need a double equal to (==) not a triple. I think triple may mean something else.

Categories