JavaScript button doesn't work - javascript

I am very new to using JavaScript so bear with me. I only finished the different courses found on Codecademy so far.
So I'm trying to make a sign up form for a website where you need a user. I found a pretty cool one on the internet that I changed a bit and also made use of the Datepicker from jQuery. It looks like this:
I got code to check whether the user filled out the different fields but it doesn't seem to work. In my index.html file I included the following file:
<script src="js/signupsubmit.js"></script>
And at the bottom of the form I do this:
<div>
<p id="sign_user" onClick="Submit()">Sign Up</p>
</div>
So good so far. In the JavaScript I have the following code:
function Submit() {
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]{2,5}$/;
var fname = document.form.Name.value,
lname = document.form.LastName.value,
femail = document.form.Email.value,
freemail = document.form.enterEmail.value,
fpassword = document.form.Password.value,
dateObject = $("#datepicker").datepicker(
{
onSelect: function()
{
var dateObject = $(this).datepicker('getDate');
}
});
if( fname == "") {
document.form.name.focus();
document.getElementById("errorBox").innerHTML = "Enter First Name";
return false;
}
if( lname == "" )
{
document.form.LastName.focus() ;
document.getElementById("errorBox").innerHTML = "Enter Last Name";
return false;
}
if (femail == "" )
{
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter your Email Address";
return false;
}else if(!emailRegex.test(femail)){
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter a Valid Email Address";
return false;
}
if (freemail == "" )
{
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter the Email Address";
return false;
}else if(!emailRegex.test(freemail)){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter a Valid Email Address";
return false;
}
if(freemail != femail){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "The Email Addresses don't Match!";
return false;
}
if(fpassword == "")
{
document.form.Password.focus();
document.getElementById("errorBox").innerHTML = "Enter a Password";
return false;
}
if(dateObject == null) {
document.form.datepicker.focus();
document.getElementById("errorBox").innerHTML = "Please Enter a Birthday";
}
}
I am a bit shaky on trying to read the Datepicker too. But otherwise, can you possibly spot what might be missing in this puzzle? When I press the blue "Sign Up" button, literally nothing happens. I can provide more info if needed.

You have a mistake addressing the form: The correct formula is not document.form, but document.forms[0]. Or even better, I recommend you to give the form a specific unique name, and address it by that name:
HTML:
<form name="mydata">...</form>
Javascript:
var fm=document.forms.mydata
Also, take care of lowercase/uppercase lettering: Identifiers in Javascript are case-sensitive, which means that the input "Name" must be always addressed as "Name" (you mispelled that identifier in the line document.form.name.focus()).

Related

Javascript else if statement not working with form validation

I'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value

Email validation doesn't capture with required fileds

I have a javascript validation function.I need to check if required fileds are empty or wrong mail address.Required fileds empty is working But when i type mail like abc#abc or something wrong then it doent catch the error in my code.
When i type all required fileds but wrong email address ( abc#abc or abc.com like doesn't capture.)
My Code
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') ||
($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
}
status = false;
}
Email Validate Function
function ValidateEmail(email) {
var expr = /^([\w-\.]+)##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
Your test for a valid email is inside the if block which test if the value is not null, so when you enter any value in the text box (whether its valid or not) the if (!ValidateEmail($("#txtemail").val())) { will never be called. Change your script to
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') || ($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
status = false;
} else if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
status = false;
}
}
Side note: All this functionality is provide out of the box in MVC by simply adding the [Required] and [EmailAddress] attribute to your property and including the relevant scripts (jquery.validate.js and jquery.validate.unobtrusive.js) and #Html.ValidationMessageFor() helpers which means you get both client and server side validation (and it's all done correctly!)

Multiple form onsubmit validations?

I have a form and currently I have a javascript code to validate my form to make sure that the user fills out every input. my form action includes:
onsubmit="return validateForm();"
Which is the javascript to make sure every field is filled out. If it makes any difference, here is my javascript code:
<script type="text/javascript">//
<![CDATA[function validateForm() {
var a=document.forms["myform"]["inf_field_FirstName"].value;
var b=document.forms["myform"]["inf_field_Email"].value;
var c=document.forms["myform"]["inf_field_Phone1"].value;
if (a==null || a=="" || a=="First Name Here")
{ alert("Please enter your First Name!");
return false; }
if (c==null || c==''|| c=="Enter Your Phone Here")
{ alert("Please insert your phone number!");
return false; }
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1)
{ alert("Please enter a valid email address.");
return false; } }
// ]]>
</script>
However on the phone number field, defined at c, I want to add another script that will pop up if the user doesn't enter a phone number at least 9 digits long. I was thinking of adding a code like this
<script type="text/javascript">
function validate(){
var c=document.forms["myform"]
if (input.length<9){
alert("Please enter a real phone number")
return false
}else {
return true
}
}
</script>
However I don't know how to run both functions on submit. I am extremely new to javascript so excuse me if there's already a simple solution to this.
Thanks
Everything in quotes after onsubmit= is just javascript. You can make sure both functions return true by doing:
onsubmit="return validateForm() && validate();"
You could add it as another rule in that conditional. For example:
if (c==null || c==''|| c=="Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
It's probably best to refactor this code, but that's probably the fastest way to do what you need.

Remaking jQuery form validation

I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});

Validating a form for ONLY letter inputs

Im validating a form but im struggling to get it to only accept letters for firstname and lastname fields
hope u can help
heres my code:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
onlyletters = "Only letters allowed.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Only Letters.
if (!/^([a-zA-Z])+$/.test(errornotice.val())) {
errornotice.addClass("needsfilled");
errornotice.val(onlyletters);
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Should this line be testing against errornotice.val() or firstname.val()?
if (!/^([a-zA-Z])+$/.test(errornotice.val())) {
// Maybe this is what you intended.
// This requires adding some more variables earlier when you set email and errornotice
email = $("#email");
errornotice = $("#error");
// Add vars for first/lastname
firstname = $("#firstname");
lastname = $("#lastname");
if (!/^([a-zA-Z])+$/.test(firstname.val())) {
firstname.addClass("needsfilled");
firstname.val(onlyletters);
}
// then do the same for lastname
if (!/^([a-zA-Z])+$/.test(lastname.val())) {
lastname.addClass("needsfilled");
lastname.val(onlyletters);
}
However, your regex of letters only is going to eliminate a lot of valid names including apostrophes, diacritics, umlauts, etc.

Categories