Javascript Validation Not Working On Click Function - javascript

I am trying to validate a form using java script on click function i.e during form submit and if condition removed the i am getting the alert message but the alert message should be shown in if condition i.e when the form is empty
$(document).ready(function(){
$('#submit').click(function(){
var name = $().val("#name");
var email = $().val("#email");
if(name == '' || email == ''){
alert("test");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<input id="name" type="text" placeholder="name">
<input id="email" type="email" placeholder="email">
<button id="submit" type="submit">submit</button>
</form>

In jQuery, input values are retrieved with $(element).val(). Your variables should look like this:
var name = $('#name').val();
var email = $('#email').val();

$(document).ready(function(){
$('#submit').click(function(){
var name = $("#name").val();
var email = $("#email").val();
if(name == '' || email == ''){
alert("test");
return false;
}
});
});

You are not selecting the input elements you want to get the values from.
Replace
var name = $().val("#name");
var email = $().val("#email");
with
var name = $("#name").val();
var email = $("#email").val();

Related

How do I select the inputted text of a text field?

I'm adding interactivity to a form.
Here is a snippet of the HTML:
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
There is a button at the bottom of the form, 'Register'. If the button is pressed and the Name field is empty, I want to add an alert message, reminding the user to enter their name. I want to do this by amending the label.
I am having trouble trying to select the inputted text of the text-field. Seeing as it's not value or innerHTML? How do I select it?
This is the code I have so far:
// Form validation. Display error messages and don't let the user submit the form if any of these validation errors exist:
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
Use .value to get the value of input field and put css value red in inverted comma as nameLabel.style.color = "red"; Also since you have a
<button type ="submit">submit</button>
you need to stop you page from refreshing. Use e.preventDefault(); for this in your event handler
The flash of error that you get while in console is that red is not defined which it isn't since its a string and you need to give it in "".
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
console.log("\"" + nameInput.value + "\"");
if(nameInput.value.length == 0) {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>

How to store data in a form so on page refresh the fields are still populated

I'm new to S.O and javascript. I am working on a final year project for a e-commerce website and have ran into a dead end on saving data from a form into local storage. My code is below, i really don't see where i have gone wrong. all help is appreciated.
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Populate the form fields
populateForm();
// Get the form
var form = document.getElementById("franchiseForm");
// Event listener for when the bookings form is submitted.
form.addEventListener("submit", function(e) {
saveData(form);
});
}
}
// Save the form data in LocalStorage.
function saveData() {
//fetch sava(data)
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//store the values
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
localStorage.setItem("address1", address1.value);
localStorage.setItem("address2", address2.value);
localStorage.setItem("city", city.value);
localStorage.setItem("pcode", pcode.value);
localStorage.setItem("phone", phone.value);
}
// Attempt to populate the form using data stored in LocalStorage.
function populateForm() {
// Fetch the input elements.
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//retrieve saved data and update the values of the form.
if (localStorage.getItem("fran_name") != null) {
name.value = localStorage.getItem("fran_name");
}
if (localStorage.getItem("name") != null) {
phone.value = localStorage.getItem("name");
}
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
}
window.onload = function(){
if (localstorage){
//populate the form fields
populateform(form);
}
}
<div id="section">
<form id="franchiseForm" action ="Order_confirmation.php" method="POST">
<div class="field">
<label for="fran_name">Franchise Name</label>
<input type="text" name="franchise_name" id="fran_name" placeholder="e.g One Delivery Leeds" pattern="[a-zA-Z]"
autofocus required tabindex="1">
<br>
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
<label for="address"> Address</label>
<input type="text" name="franc_address" id="address1" placeholder="Address Line 1" tanindex="3">
<input type="text" id="address2" placeholder="Address Line 2" tabindex="4">
<input type="text" id="city" placeholder="Town/City" tabindex="5">
<input type="text" id="pcode" placeholder="Postcode" tabindex="6">
<br>
<label for="phone" > Phone Number</label>
<input type="tel" name="franc_phone" id="phone" placeholder="Customer service number" min="10" maxlength="11" pattern="[0-9]{3}[-][0-9]{4}[-][0-9]{4}"
required title="Please provide your customer service number in the following format: 000-0000-0000" tabindex="7">
</div>
<div class="field">
<input type="submit" id="submit" value="submit">
</div>
</form>
The main thing is, check your console for this error:
Uncaught ReferenceError: localstorage is not defined.
Change your code. It is localStorage and not localstorage. That's a capital S.
And a big mistake here. It is getElementById and not getElemenyById:
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
You have too many mistakes! Elemeny != Element.
Looks like this is stopping your code from executing:
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
You don't have a variable named email. And moreover, you are trying to set the value of an undefined element variable email, which doesn't have a property named value, that prevents all your scripts from executing.
First of all, not in your code you use:
document.getElemenyById(...);
localstorage.setItem()
instead of (note the Elemeny vs. Element, s vs. S):
document.getElementById(...);
localStorage.setItem();
As for a full solution:
You can use various local storage to store this data in the browser.
You can do something like this when the page is about to reload:
window.onbeforeunload = function() {
var fran_name = document.getElementById("fran_name");
var name = document.getElementById("name");
// ...
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
// ...
}
localstorage works synchronously so this will work here.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
getItem will return null` if the data does not exist.
Use sessionStorage instead of localStorage if you want to store temporarily - until the browser is closed.
Here's a simplified version of your form, with complete working code. save it as a .html file:
<html>
<head>
<script type="text/javascript">
// For saving data:
window.onbeforeunload = function() {
var name = document.getElementById("name");
// ...
localStorage.setItem("name", name.value);
// ...
}
// For loading data:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
</script>
<title></title>
</head>
<body>
<div id="section">
<form id="franchiseForm" action="Order_confirmation.php" method="POST">
<div class="field">
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
</div>
</form>
</div>
</body>
</html>
If you are able to use JQuery and JQuery Cookie, you can save the data in a cookie:
var frn = $(#fran_name).val();
$.cookie("fran_name", frn);
Then on pageload you get the cookie data and then insert it into the field:
$(document).ready(function(){
var cookie = $.cookie("fran_name");
$('#fran_name').val(cookie);
});

How can I use validation with form without page refresh?

I am using a jQuery for mobile number validation without page refresh on submit button but it is not working and when I click the submitbutton. But with page refresh it works.
Here is my code:
index.html
<html>
<head>
<title>Submit Form Without Refreshing Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/refreshform.css" />
<script src="js/fresh.js"></script>
</head>
<body>
<div id="mainform">
<!-- Required div starts here -->
<form id="form">
<label>First Name:</label>
<br/>
<input type="text" id="fname" placeholder="First Name"/><br/>
<br/>
<label>Last Name:</label>
<br/>
<input type="text" id="lname" placeholder="Last Name"/><br/>
<br/>
<label>MobliNo:</label>
<br/>
<input type="text" id="mobile" placeholder="Your MobNo"/><br/>
<br/>
<label>ConfirmMobliNo:</label>
<br/>
<input type="text" id="remobile" placeholder="Confirm MobNo"/><br/>
<br/>
<label>Email:</label>
<br/>
<input type="text" id="email" placeholder="Your Email"/><br/>
<br/>
<input type="button" id="submit" value="Submit" onclick = "return Validate()"/>
</form>
</div>
</body>
</html>
refresh.js
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
});
});
function Validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^\d{10}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : " + mobile);
return true;
}
alert("It is not valid mobile number.input 10 digits number!");
return false;
}
What should I do to achieve validation without page refresh?
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
should be
$('#form').submit(function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
or *)
$('#form').on('submit', function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
By including event.preventDefault() in the event handler, you block the default action for the element that triggered the event. In this case, the default action is submitting the form, so without this change, the form will still be submitted in the normal way, after it is submitted through AJAX.
*) Side note: on is a bit more flexible for binding events. You can also specify a selector as the second parameter. This way, you can set an event handler in the document (or another containing element), which will automatically be called for events on any child element that matches the given selector. This is especially useful if you have dynamic pages where elements are added or removed, because you won't have to add the event handlers every time you add an element. In this particular case it won't matter much, but I thought I'd let you know. The syntax for that is:
$(document).on('submit', '#form', function(event){
Do it in a slight different way. Remove
onclick = "return Validate()"
from the button and put that inside the click function like this
$("#submit").click(function(){
var valid = Validate();
if(valid){
/// Then your rest of process here.
}
});
Hope that works.
This will just check whether the phone number has 10 digits
function Validate() {
var mobile = document.getElementById("mobile").value;
var remobile = document.getElementById("remobile").value;
if(isNaN(mobile) || isNaN(remobile)){
alert("Invalid. Mobile and re mobile should be numbers only.");
return false;
}
if(mobile.length != 10){
alert("Invalid number. It should be 10 digits only.");
return false;
}
if(remobile.length != 10){
alert("Invalid Re mobile number. It should be 10 digits only.");
return false;
}
if(mobile != remobile){
alert("Mobile and remobile does not match!");
return false;
}
alert("Valid Number.");
return true;
}
in you form use:
<form id="form" onsubmit="return Validate();">
and button just submit:
<input type="submit" id="submit" value="Submit" />
in your js validate code instead of return true
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
return false;
in this case you will submit form without page refresh
function Validate() {
var mob = /^[1-9]{1}[0-9]{9}$/;
if (mob.test($.trim($("#<%=mobile.ClientID %>").val())) == false) {
alert("Please enter valid mobile number.");
$("#<%=mobile.ClientID %>").focus();
return false;
}

Input type password value is showing as null

I don't understand why my is not giving the value properly to my javascript variable. I have tried countless times, changing IDs and whatnot... still nothing... I searched everywhere for an answer... Please help
HTML SNIPPET
<form action="" method="post" onsubmit= "return validateForm()" class="registerform">
First Name: <input type="text" name="fname" id="fname"><br/>
Last Name: <input type="text" name="lname" id="lname"><br/>
Email: <input type="text" name="email" id="email"><br/>
Phone Number: <input type="text" name="phone" id="phone"><br/>
Password: <input type="password" name="password" id="myPass"><br/>
Confirm Password: <input type="password" name="confirmpassword" id="confirmPass"><br/>
<p><input type="submit" value="Submit"></p>
</form>
register.js
...
var password = document.getElementById("myPass").value;
var confirmPassword = document.getElementById("confirmPass").value;
...
function validateForm()
{
alert(password);
alert(confirmPassword);
error = '';
var fNamePass = validateFName();
var lNamePass = validateLName();
var emailPass = validateEmail();
var phonePass = validatePhone();
var passwordPass = validatePassword();
var passwordConfirmPass = validateConfirmationPassword();
...
in my alerts, the value keeps showing as null. Firebug shows me the value at null...
I'm not new to JS, but I feel like I'm doing something really silly here, but my mind is not catching it...
I think you are running into a scoping issue.
You need to make sure you pass the 'password' and 'confirmPassword' argument on to the function.
Fine... do it the same way you did the rest
function validateForm()
{
var password = validatePassword();
var confirmPassword = validateConfirmPassword();
alert(password);
alert(confirmPassword);
error = '';
var fNamePass = validateFName();
var lNamePass = validateLName();
var emailPass = validateEmail();
var phonePass = validatePhone();
var passwordPass = validatePassword();
var passwordConfirmPass = validateConfirmationPassword();
You are setting the value of password and confirmpassword at time of load of document.
Move your definition of password and confirmpassword inside the function
var password, confirmPassword;
function validateForm()
{
password = document.getElementById("myPass").value;
confirmPassword = document.getElementById("confirmPass").value;
alert(password);
alert(confirmPassword);

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;
}

Categories