I have a simple form and I am using javascript for validation of data entered. I can't understand why document.getElementById("submitform").submit() is not working. Below is my code. Thank you for your help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function checkSyntax(){
jsid=document.getElementById("sid").value;
jname=document.getElementById("name").value;
jemail=document.getElementById("email").value;
jgpa=document.getElementById("gpa").value;
var noError=true;
var Regsig=/^[2][0-9]{8}$/;
var Regn=/^[a-zA-Z]{2,25}$/;
var Rege=/^[a-zA-Z]+[_]?[a-zA-Z]*[#][a-zA-Z]+[.](net|com|edu.sa)$/;
var Regg=/^[1-4]+[.][0-9]+/;
if(!Regsig.test(jsid)){
alert("The student ID must be all numbers and of length 9");
noError=false;
}
if(!Regn.test(jname)){
alert("Name must be alphabets of min length 3 and max 25");
noError=false;
}
if(!Rege.test(jemail)){
alert("Wrong email format");
noError=false;
}
if(!Regg.test(jgpa)){
alert("Wrong GPA format");
noError=false;
}
if(noError){
**document.getElementById("submitform").submit();**
}
}
function checkRetrieve(Sid2,Name2){
var Regsig=/(|[2][0-9]{8})/;
var Regn=/(|[a-zA-Z]{2,25})/;
var error=true;
if(!Regsig.test(sid.value)){
alert("The student ID must be all numbers and of length 9");
error=false;
}
if(!Regn.test(name.value)){
alert("Name must be alphabets of min length 3 and max 25");
error=false;
}
if(Sid2.value!="" && Name2.value!=""){
alert("you can only use on of the two fields for your query");
Sid2.value="";
Name2.value="";
error=false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<h1>Web-Based Application for Student Academic Records</h1>
<p> Add a new student</p>
<body>
<form id="submitform" name="form1" method="post" action="stacademic.php">
Student ID:<input type="text" size="26" maxlength="9" name="SID"id="sid"/><br /><br />
Name:<input type="text" size="30" maxlength="50" name="NAME" id="name"/><br /><br />
Email:<input type="text" size="30" maxlength="50" name="EMAIL" id="email"/><br /><br />
Major: <select id="major" name="MAJOR">
<option>Computer Engineering<option/>
<option>Computer Science<option/>
<option>Electrical Engineering<option/>
<option>Mechanical Engineering<option/>
<option>Software Engineering<option/>
</select><br />
<br />
GPA:<input type="text" size="30" maxlength="5" name="GPA" id="gpa"/><br /><br />
<input type="submit" value="submit" onclick="checkSyntax()" name="submit"/><br />
</form><br />
<p> Retrieve student GPA either Student ID or Student Name: </p>
<form id="retrieveform" onSubmit="return checkRetrieve(this.sid2,this.name2);" method="post" action="stacademic.php">
Student ID:<input type="text" size="26" maxlength="9" name="SID2" id="sid2"/><br /><br />
Name:<input type="text" size="30" maxlength="50" name="NAME2" id="name2"/><br /><br />
<input type="submit" value="Retrieve Results" name="submit2"/><br />
</form>
</body>
</html>
When you click the button, the form is already being submitted.
What you should to is to assign the checkSyntax to the onsubmit event and then return true if everything was right or return false if errors occurs. If the function in the onsubmit event returns false, the form is not submitted.
Alex is right, your submit button is submitting the form. You should use the onSubmit event on your form and if validation fails, have it return false, which will cancel the submit. Also, it is not a good idea to use onclick because if the user submits the form by hitting enter, the function will be bypassed.
<form id="submitform" name="form1" method="post" action="stacademic.php" onSubmit="checkSyntax()">
Related
I am new to HTML and JavaScript. I just made a simple page to add two numbers. The output that I am getting is correct but when I click the sum button the sum is there for a fraction of second and then again the page reloads itself.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum() {
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum()">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
You need to pass the event and add event.preventDefault(); at the beginning of the function to prevent page from reloading since it's a submit button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum(event)">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
The onsubmit must return false to prevent browser from submitting it to server.
Like this
<form id="form" onsubmit="get_sum(); return false;">
You can add an event listener to handle the click after you change the type to "button". Or you can stop the event from propagating to the actual "submit" action. OR, do both to prevent the submit of the form.
Why both? A form can also be submitted by hitting "return/enter" or via script.
This is perhaps a bit of overkill but shows how to handle the events.
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
const sumButton = document.getElementById('sum-click');
sumButton.addEventListener("click", get_sum, false);
const form = document.getElementById('form');
form.addEventListener('submit', get_sum);
<form id="form">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button id="sum-values" type="submit">Sum </button>
<button id="sum-click" type="button">Sum (Not submit)</button>
</form>
<h1 id="sum"></h1>
I m applying two validation but both are not work
required validatation not work on input attribute
function validatation() not work
signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="signup.js"></script>
<script type="text/javascript">
function validatation() {
debugger
if (document.PersonalInform.txtfname.value == "") {
debugger
alert("Please provide your first name!");
document.PersonalInform.Name.focus();
return false;
}
}
</script>
</head>
<body>
<form id="txtPersonalInformation" name="PersonalInform" onsubmit="return (validatation());">
<h1>Personal Information</h1>
First Name:<input id="txtfname" name="txtfname" type="text" /><br/>
Middle Name:<input id="txtmname" name="txtmname" type="text" /><br/>
Last Name:<input id="txtlname" name="txtlname" type="text" /><br/>
<input id="btnnext" type="button" value="Next" />
</form>
</body>
</html>
OR
Below Validation Also Not Work
First Name:<input id="txtfname" name="txtfname" type="text" required /><br/>
signup.js
$(document).ready(function () {
$('#btnnext').click(function (event) {
$("#txtPersonalInformation").load("ContactInformation.html");
});
});
I add this line in web.config file
web.config
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
</appSettings>
I want to perform this javascript function validation but not work?
function validatation()
Here's what you want. You weren't submitting you form, as noted by Mendrika.
HTML Form:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> type="text/javascript"></script>
<form id="some-form" action="some-url" onsubmit="return validate()">
<label for="first-name">First Name:</label>
<input id="first-name" name="first-name" type="text"><br>
<label for="last-name">Last Name:</label>
<input id="last-name" name="last-name" type="text"><br>
<input id="btn-submit" type="submit" value="Submit">
</form>
JS Sample Validate function
function validate() {
if ($("#first-name").val() === "") {
alert("Provide a first name");
$("#first-name").focus();
return false;
}
if ($("#last-name").val() === "") {
alert("Provide a last name");
$("#last-name").focus();
return false;
}
return true;
}
https://codepen.io/el-sa-mu-el/pen/QWjVGvb
Note, this is not good code, but it works. You should read more about basics of JS and form validation.
Some other observations:
Your form is missing the action=" " tag which actually POSTs the data to some URL. Where is your data going?
You are mixing vanilla Java Script and JQuery. Use JQuery for DOM access if you already included it, with the $ symbol.
You have a signup.js function but also include a Javascript function in the <script> tags. You can move the validate() function into the signup.js
Better form validation with JQuery:
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
The reason nothing works is because your form is never submitted.
You just need to change the next button type to submit.
<input id="btnnext" type="submit" value="Next"/>
I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.
I have a form in which the user inputs various information. The input chosen name allows the user to enter a username of choice but a HIDDEN INPUT needs to be integrated so that a system username is created.
The system username is generated on page submit by a javascript function, and it consists of the first alphabetic characters found in the Family name, street address, Given name; the numerical day of the month; and the numerical seconds field of the time of submission. E.g.: A user registers with name Bernardo O’Higgins, address 213 Liberator St, at 12:31:16 on 25 April 2014. His system username is
OLB2516. Just so i can see if it works, at the moment the ssytem username is not hidden but just a normal text box.
I am totally lost as i do not know how to go about this and hoping somebody can help me? Here is my php file with form integrated.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<title>Registration</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "....", ".....");
mysql_select_db("tipping291", $conn)
or die ('Database not found ' . mysql_error() );
mysql_close($conn);
?>
<div id="container">
<div id="header">
<h1>Registration</h1></div>
<div id="menu">
<h2>Homepage</h2><br />
<h2>Registration</h2><br />
<h2>User Login</h2><br />
<h2>Administrator Login</h2><br />
<h2>Tipping</h2><br />
<h2>Terms & Conditions</h2><br />
</div>
<form id="rego" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" onSubmit="return validateForm()">
<label>Given Name:</label> <input type="text" name="gname"><br />
<br />
<label>Middle Name: </label><input type="text" name="mname"><br />
<br />
<label>Family Name:</label> <input type="text" name="surname"><br />
<br />
<label>Chosen Username:</label> <input type="text" name="username"><br />
<br />
<label>Address:</label> <input type="text" name="address"><br />
<br />
<label>Postcode: </label><input type="text" name="postcode"><br />
<br />
<label>State:</label> <input type="text" name="state"><br />
<br />
<label>Tel number: </label><input type="text" name="tel"><br />
<br />
<label>Password:</label> <input type="password" name="password"><br />
<br />
<label>Password confirmation:</label> <input type="password" name="passconfirm"><br />
<br />
<label>System username</label> <input type="text" name="susername" >
<input type="submit" value="submit">
</div>
</form>
</body>
</html>
CAN SOMBODY PEASE HELP ME!!!!! I HAVENT HAD ANY SUCCESSS
I think the code found here is more suitable to generate a random string (you can put 20 characters instead of 10)
You can also just use md5() in the time or user email...
And you don't need to worry to create it in javascript, if this is random generated you can do that in php.
If you really need to do in javascript... there's CaffGeek answer in this post.. who could help you
Add the below code before closing } of function validateForm() { and try
var username = '';
var date = new Date();
$.each(['surname', 'address', 'gname'], function() {
username += $.trim($('input[name="' + this + '"]').val().replace(/\d+/g, '')).substring(0, 1);
});
username += date.getDate() + '' + date.getSeconds();
$('input[name="susername"]').val(username);
jsBin
<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
User Name:<br />
<input type="text" name="userName" size="25" /><br />
Password:<br />
<input type="password" name="pw" size="25" /><br />
<input type="submit" value="Log In" onClick="validate()"/>
</form>
Thats my HTML, I have figured out how to only get alpha numerical data into the fields, but how do I get it to only allow a User Name that starts with a capital?
<script language="javascript">
</script>
The simplest way to check this is with a regular expression:
function(str){
return /^[A-Z]/.test(str);
}
returns true when the input string starts with a capital, false otherwise. (This particular regular expression - the bits between the // characters - is saying, 'match the start of the string followed by any single character in the range A-Z'.)
In terms of your HTML above, we'll need the contents of the validate() function to determine where the regex match needs to go.
In your validate function, use a regex match like this:
if (titleString.match(/^[A-Z]/))
<ok>
var letter = str[0];
if (letter !== letter.toUpperCase()){
//not uppercase!
}
This will check to see if the username entered starts with a capital letter, and is followed by 5 - 24 alphanumeric characters.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validate() {
var the_input = document.getElementById('userName').value;
if (!the_input.match(/^[A-Z]([A-Z]|[a-z]|[0-9]){5,24}$/)) {
alert('Your username must begin with a capital letter, and contain between 6 and 25 alphanumeric characters.');
return false;
} else {
alert('Welcome!');
return true;
}
}
</script>
</head>
<body>
<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
User Name:<br />
<input type="text" name="userName" id="userName" size="25" /><br />
Password:<br />
<input type="password" name="pw" size="25" /><br />
<input type="submit" value="Log In" onclick="return validate();"/>
</form>
</body>
</html>
As an aside, it should be noted that this will not work if the user has javascript turned off - you may wish to have some server-side validation instead (or in addition) as a fail-safe.