I defined a function to validate the input fields based on a pattern string I specified. For the name fields, I made sure to specify only english letters are allowed, but when I type in number into name field and submit my form, it doesn't alert me.
function validate() {
//first, get the input fields to validate!
var first_name = document.getElementById("fname");
var last_name = document.getElementById("lname");
var email = document.getElementById("email");
var date = document.getElementById("date");
//lay out the pattern expected for name, email, and date!
var name_pattern = "/^[a-zA-Z]{2:30}/";
var email_pattern = "/^[a-zA-Z0-9]{3:20}#[a-zA-Z0-9]{3:20}.[a-z]{3:5}/";
var date_pattern = "/^[0-9]{2}/[0-9]{2}/[0-9]{2}/";
if (name_pattern.test(first_name.value)) {
alert("Make sure to type in first name using only letters (max length of 30)!");
}
if (name_pattern.test(last_name.value)) {
alert("Make sure to type in last name using only letters (max length of 30)!");
}
if (email_pattern.test(email.value)) {
alert("Make sure to type in valid email with characters and numbers before and after #! Also, make sure to end with valid domain!");
}
if (date_pattern.test(date.value)) {
alert("Make sure to input date in MM/DD/YYYY format!");
}
}
<h1 id="form_header">
Get in Touch Form
</h1>
<form>
<ul>
<li>
<label for="fname">First Name:</label>
<input id="fname" type="text" name="user_fname" value="Ex. John" maxlength="30" required />
</li>
<li>
<label for="lname">Last Name:</label>
<input id="lname" type="text" name="user_lname" value="Ex. Doe" maxlength="30" required />
</li>
<li>
<label for="email">Email:</label>
<input id="email" type="email" name="user_email" value="Ex. john_doe#gmail.com" required />
</li>
<li>
<label for="date">Today's Date:</label>
<input id="date" type="date" name="user_date" value="Ex. 11/23/2022" required />
</li>
<li>
<label for="employer">Are you an employer?</label>
<input id="employer" type="checkbox" name="user_is_employer" />
</li>
<li>
<label for="message">Message:</label>
<textarea id="message" name="user_message"></textarea>
</li>
<li class="button">
<button type="submit" onsubmit="validate()">
Submit!
</button>
</li>
</ul>
</form>
I don't know what's wrong since I included script tag in my corresponding html file and made sure the function name is correct as well. What should I do?
Related
I'm building a simple form but I'm stuck:
if I send only the email field, the form validates the email and sends it
if I add two fields I can't get it to work:
name
checkbox (GDPR)
I need to add the validation that the name field is not empty, and that the checkbox field is checked
$(document).ready(function($) {
var jsForm = $('.js-form-download');
jsForm.on('submit', function(e) {
var email = $(this).find('input[type=text]').val();
if (!validateEmail(email)) {
e.preventDefault();
jsForm.addClass('form-error');
}
});
// VALIDATION BEGIN
function validateEmail(email) {
var re = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
return re.test(email);
}
//VALIDATION END
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form accept-charset="UTF-8" action="/form.php" method="POST" class="main-download-form text-center js-form-download">
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
<input class="infusion-field-input-container" id="inf_field_Email" name="email" type="text" placeholder="Enter Your Email Address" autocomplete="off" required="">
<!-- field GDPR 1 REQUIRED -->
<div class="form-single--checkbox" style="max-width:400px; margin: 0 auto 20px;">
<label style="font-weight:normal;"><input type="checkbox" id="pcheck" style="width:18px; height: 18px; margin-left:0%; margin-bottom:0px;"/>Accetto il Regolamento della <strong>Privacy</strong>
</label>
</div>
<input class="btn-full" type="submit" value="Continue...">
</form>
Your issue is here var email = $(this).find('input[type=text]').val();
this will give you the first INPUT element's .val(), and if you take a closer look, the first INPUT in your form is actually the name
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
So, not the email one.
Instead, use:
var email = $(this).find('[name=email]').val();
Or, since you already use ID selectors in your HTML
var email = $("#inf_field_Email").val();
When I enter invalid details the website doesn't show up with any errors and it sumbits the form
I've tried putting onsubmit on the form tag and onclick on the button tag but nothing works
it should come up with an error when I type in an invalid email or postcode or the passwords dont match
also I would like it so that when the user inputs numbers for the first name or last name it comes up with an error
<form class="modal-content" action="register.php" method="post" name="myform">
<div class="signup-container">()
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<div class="fbox">
<label for="fn"><b style="font-size:14px;">First Name</b></label>
<input type="text" id= "First_Name" placeholder="Enter First Name" name="fname" required>
</div>
<div class="sbox">
<label for="ln"><b style="font-size:14px;">Last Name</b></label>
<input type="text" id= "Last_Name" placeholder="Enter Last Name" name="lname" required>
</div>
<div class="tbox">
<label for="email"><b style="font-size:14px;">Email</b></label>
<input type="text" id="Email" placeholder="Enter Email" name="email" required>
</div>
<div class="fobox">
<label for="pc"><b style="font-size:14px;">Post Code</b></label>
<input type="text" id="pcode" placeholder="Postcode" name="pcode" required>
</div>
<div class="fibox">
<label for="psw"><b style="font-size:14px;">Password</b></label>
<input type="password" id="pass" placeholder="Enter Password" name="pass" required>
</div>
<div class="sixbox">
<label for="psw"><b style="font-size:14px;">Confirm Password</b></label>
<input type="password" id="UserPassword" placeholder="Confirm Password" name="UserPassword" required>
</div>
<label class="remember">
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button onclick="validateform()"type="submit" name="Submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
<script>
function validateform(){
var Firstname = document.querySelector( "#First_name"); //sets the variable name as the value entered by the user
var Lastname = document.querySelector( "#Last_Name"); //sets the variable name as the value entered by the user
var password = document.querySelector( "#pass");//sets the variable password as the value entered by the user
var confirmpassword = document.querySelector( "#UserPassword");//sets the variable confirmpassword as the value entered by the user
var email = document.querySelector( "#Email");//sets the variable email as the value entered by the user
var atposition = email.indexOf("#");
var dotposition = email.lastIndexOf(".");
var postcode = document.querySelector("pcode");//sets the variable postcode as the value entered by the user
function alertMessage(messageObject) {
alert(messageObject);
return true;
}
if (Firstname==null){
alertMessage("Firstname can't be blank"); //makes sure that the name is not empty
return false;
}else if (Lastname==null){
alertMessage("Lastname can't be blank"); //makes sure that the name is not empty
return false}
else if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email.length){
alertMessage("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition); //makes sure email is in the right format
return false;
}
function valid_postcode(postcode){
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
valid_postcode(postcode)
if(password.length<8){
alertMessage("Password must be at least 8 characters long."); //makes sure password is above 8 characters
return false;
}
else if(password!==confirmpassword){
alertMessage("password must be same!"); //makes sure that the passwords match
return false;
}
}
You should change your html type code from "submit" to "button", for the page not submit by it self. And put a id="myform" in your form.
<form class="modal-content" action="register.php" method="post" name="myform" id="myform">
<button onclick="validateform()" type="button" name="Submit" class="signupbtn">Sign Up</button>
And put this code on your javascript, you could do a verification to check if everything is ok, then you call this function to submit your form.
javacript
document.getElementById('myForm').submit();
I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".
I have a script to count the words in an attachment which works fine.
function loadDemo() {
WordCount.words("file_attach", function(words) {
document.getElementById("words").innerText = words;
});
var elt = document.getElementById("words");
var words = elt.options[elt.selectedIndex].value;
words = parseInt(words);
var tprice = (words /500) * 12;
document.getElementById("tprice").innerText=tprice;
}
I then wanted to calulate a price which is printed in span box below.
The word count is printed to its span, but price is not. Where have i gone wrong in my calculation?
<div id="result"></div>
<label for="name"><span>Name</span>
<input type="text" name="name" id="name" placeholder="Enter Your Name" />
</label>
<label for="email"><span>Email Address</span>
<input type="email" name="email" id="email" placeholder="Enter Your Email" />
</label>
<label for="file"><span>Attachment</span>
<input type="file" name="file_attach" id="file_attach" onChange="loadDemo()" />
</label>
<label for="words"><span>No. of Words</span>
<span id="words"></span>
</label>
<label for="tprice"><span>Price</span>
<span id="tprice"></span>
</label>
<label for="message"><span>Message</span>
<textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
</label>
<label><span> </span>
<button class="submit_btn" id="submit_btn">Submit</button>
</label>
Above is HTML of form.
Thanks
Your JavaScript for looking up the words is:
var elt = document.getElementById("words");
var words = elt.options[elt.selectedIndex].value;
but the second line is what you'd use for retrieving values from a select dropdown. The element <span id="words"></span> however is not a select element. You need to use:
var elt = document.getElementById("words");
var words = elt.textContent;
Demo
As a side note, it's a bit unusual to use <label> tags for things that aren't form controls. Specifically there's no point in using the label's for attribute to point to a non-input element because they can't receive focus.
I am creating an onlineshop and I want to use Javascript ( I think) or JQuery, in order when the user is entering details for adding a new product into the database, like:
-Title (TEXT)
-Price (FLOAT)
-Description (TEXT)
-Quantity Available (INT)
How to set a check to occur and inform the user that he has an incorrect data type for a specific field? Because now my database lets the user add whatever he wants, and at the preview of the product the field price shows "£0". Also, if the check completes for all the fields and is okay, a message will be shown that it okay.
code below
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<div id="formContents">
<label for="title">Title of your product:
<div id="formContents"> </label><input type="text" name="title" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value=" title of your product here" maxlength="19" /><p>
</div>
<div id="formContents">
<label for="description">Description of your product:
<div id="formContents"> </label><input type="text" name="description" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="description of the product" maxlength="19" /><p>
</div>
<label for="price">Price: £ </label><input type="INT" name="price" style="width: 40px" /><p>
<label for="stock">Quantity:</label><input type="text" name="stock" style="width: 40px" />
<p>
</div>
you can do it two ways:
prevent him from entering anything other than intended characters :
for example , for fields that would have INT values :
$('.nonly').bind('keyup blur',function(){$(this).val($(this).val().replace(/[^0-9]/g,''));});
validate after entering :
var intRegex = /^\d+$/;
var cellphone = $('#register_phonenum');
if ((cellphone.val()=='')||(!intRegex.test(cellphone.val()))) {
/* do something*/
return false;
}