JavaScript: Form not validated with OnSubmit - javascript

I am new bee to JavaScript. I have a form which is not validated with alert button. I am having a form which is to be submitted without errors. If I submit the forms with the empty fields, an alert message should be popped up.
The following is my code:
function validate_Form() {
alert('hi how');
exit;
var tokenNo = document.forms["myForm"]["txt1"].tokenNo;
if (tokenNo == null || tokenNo == "") {
alert("Enter The Token No");
return false;
} else {
document.write("pola");
}
}
<table>
<form name="Sec_guard_form" onsubmit="validate_Form()">
<tr>
<td>Token No</td>
<td>
<input type="text" value="" name="token_no" />
</td>
</tr>
<tr>
<td>Other Property</td>
<td>
<input type="text" value="" name="other_prop" />
</td>
</tr>
<tr>
<td>Bike Number</td>
<td>
<input type="text" value="" name="bike_no" />
</td>
</tr>
<tr>
<td>bike name</td>
<td>
<input type="text" value="" name="bike_nm" />
</td>
</tr>
<tr>
<td>bike model</td>
<td>
<select option="bike model">
<option value="Activa 3G">Activa 3G</option>
<option value="shine">shine</option>
<option value="unicon">unicon</option>
<option value="yuga">yuga</option>
<option value="neo">neo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" />
</td>
<td>
<input type="submit" value="cancel" />
</td>
</tr>
</form>
</table>
The above is my code, for i am using the mozilla firefox as my browser. Is that an issue. My function inside the script is not even called. what am i wrong here...

You can change your javascript like this :
function validate_Form() {
var form = document.querySelector("form");
var tokenNo = form.elements.token_no.value;
if (tokenNo == null || tokenNo == "") {
alert("Enter The Token No");
return false;
} else {
document.write("pola");
}
return false;
}
and your html like this:
<form name="Sec_guard_form" onsubmit="return validate_Form()">
exit; doesn't mean anything in javascript. You have to use return. So if you return before the function does anything then it is not useful at all!
The syntax you used for selecting form element and getting its value was wrong according to me so I corrected the syntax...
Also, you might be wondering why to use return validate_form() in HTML and return false in the function. It is used just for stopping the page to refresh/redirect before the entire function gets executed!
Try this code, it worked for me... I don't know what hi how was for so I eliminated it.

You are not calling function on your submit button Please use this to call function first.
<input type="submit" value="submit" onclick="validate_Form()" />

change
<form name="Sec_guard_form" onsubmit="validate_Form()">
to
<form name="Sec_guard_form" onsubmit="return validate_Form()">

Complete html code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<table>
<form id="Sec_guard_form" onsubmit="return validate_Form();" method="post">
<tr>
<td>Token No</td>
<td>
<input type="text" value="" name="token_no" />
</td>
</tr>
<tr>
<td>Other Property</td>
<td>
<input type="text" value="" name="other_prop" />
</td>
</tr>
<tr>
<td>Bike Number</td>
<td>
<input type="text" value="" name="bike_no" />
</td>
</tr>
<tr>
<td>bike name</td>
<td>
<input type="text" value="" name="bike_nm" />
</td>
</tr>
<tr>
<td>bike model</td>
<td>
<select option="bike model">
<option value="Activa 3G">Activa 3G</option>
<option value="shine">shine</option>
<option value="unicon">unicon</option>
<option value="yuga">yuga</option>
<option value="neo">neo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" />
</td>
<td>
<input type="submit" value="cancel" />
</td>
</tr>
</form>
</table>
<script>
function validate_Form()
{ alert('hi how');
var tokenNo = document.getElementById("Sec_guard_form")["token_no"].value;
if (tokenNo == null || tokenNo == "")
{
alert("Enter The Token No");
return false;
}
else
{
document.write("pola");
}
}
</script>
</body>
</html>
This is working fine

Related

My form's validate() is not working

NOTHING IS WORKING! I added onSubmit = "validate()" to my register button in the form, and I made the function and the alert if the fields are left empty. But NOTHING IS WORKING!
No alerts no errors in console. No hope!
<head>
<title>WHAT THE TECH!</title>
<script type="text/javascript">
function validate() {
let fullname = document.getElemenyByname("full_name").value;
let email = document.getElemenyById("email").value;
let pass = document.getElemenyById("password").value;
let add = document.getElemenyById("address").value;
if (fullname == "" || fullname.length == 0) {
alert("Enter Full Name");
document.getElemenyById("full_name").focus;
return false;
} else if (email == "" || email.length == 0) {
alert("Enter Email Address!");
document.getElemenyById("email").focus;
return false;
}
}
</script>
</head>
<body>
<div class="mainwrap">
<div class="content">
<div class="SignUp">
<div class="Formup">
<div class="title">New here? Register!</div>
<form name="register">
<table>
<tr>
<td>Full Name: </td>
<td><input type="text" id="full_name">
</td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email">
</td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password">
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<select>
<option value="U.A.E">U.A.E</option>
<option value="K.S.A">K.S.A</option>
<option value="Qatar">Qatar</option>
</select>
</td>
</tr>
<tr>
<td>Gender: </td>
<td>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</td>
</tr>
<tr>
<td>Address: </td>
<td><input type="text" id="address">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Register" class="registerbutton" name="register" onSubmit="validate()">
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
You should use document.getElementsByName if you want to fetch the value using name attribute. I would recommend to do it by "id" attribute.
function submitFunction() {
var firstName = document.getElementsByName("first_Name")[0].value;
if (firstName == "" || firstName == null || firstName.length == 0) {
alert("First Name is required");
return false;
}
}
Also add return to the onsubmit event to avoid page refresh.
<form name="Register" onsubmit="return submitFunction() " method="post">
Option 2 : Using HTML5
The required attribute will do the validation check and you can skip javascript.
<input type="text" name="first_Name" required>

jQuery .submit() function not working inside of .ready() function

I have a Classic ASP application which uses a dynamic table to submit inventory information. All of my functions inside the jQuery script until I get down to the .submit() part. I am trying to check that an employee number is given as well as that there are no blank fields before the form is submitted. Any help?
Here's my form:
<form name="filter" id="theForm" method="GET" action="InventoryIssues.asp">
<table class="normsideBG" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td class="bigger headerBG" align="center" colspan=6>
<b>Inventory Issues</b>
</td>
</tr>
<tr class="norm">
<td>
</td>
</tr>
<tr class="norm">
<td class="norm" align ="right">
<b>Enter Employee Number: </b><input type="text" id="employeeNum" name="employeeNum" value = "<%=employeeNum %>" />
<select id="hiddenBox" name="hiddenBox" style="display: none" >
</select>
<input type="hidden" name="action" value="set_filter">
</td>
</tr>
<tr>
<td class="norm">
To add more records click 'Add New Record'. Submit when all records are completed.
<br />
<br />
<input style="text-align: right" type="hidden" name="hasValues" value="false" />
<center>
<button type="button" id="addRec">Add New Record</button>
<button type="button" id="delRec">Remove Last Record</button><br /><br />
<input type="submit" id="sub" name="submit" class="norm" value="Submit"/>
</center>
</td>
</tr>
</table>
<table id= "tb1" class="norm sideBG" name="recordTable" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td>
<b><u>PART #</u></b>
</td>
<td>
<b><u>LOCATION</u></b>
</td>
<td>
<b><u>QUANTITY</u></b>
</td>
<td>
<b><u>WHERE USED</u></b>
</td>
</tr>
<tbody class="theRow" id="theRow">
<tr>
<td class="norm">
<label id="partLabel" style="color : red;"></label>
<br />
<input type='text' name='txtbox0[]' id='txtbox0[]' onchange="javascript: changeLabel(this)" />
</td>
<td class="norm">
<select id="txtbox1[]" name="txtbox1[]" >
</select>
</td>
<td class="norm">
<input type='text' name='txtbox2[]' id='txtbox2[]' />
</td>
<td class="norm">
<input type='text' name='txtbox3[]' id='txtbox3[]' />
</td>
</tr>
</tbody>
</table>
</form>
Here is my jQuery
'<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var ctr = 0;
$("#addRec").click(function ()
{
var clone = $("#tb1 > tbody.theRow:last").clone();
clone.find("input").val("");
clone.insertAfter("#tb1 > tbody.theRow:last");
$("#hasValues").val(true);
});
$("#delRec").click(function ()
{
$("#tb1:last tbody.theRow:last").remove();
});
alert("at least this works");
$("form#theForm").submit(function(event)
{
var blankEmployeeNum;
var blankFields = false;
var inp = $("#employeeNum");
if (inp.val().length == 0 || inp.val() == Null)
{
alert("blank empoyee num");
blankEmployeeNum = true;
}
else
{
alert("the employee num has a value");
blankEmployeeNum = false;
}
$("#tb1 tr").each(function()
{
$("td", this).each(function()
{
var value = $(this).find(":input").val()
if (value.val().length == 0 || value.val() == Null)
{
alert("there's a blank field");
blankFields = true;
}
});
});
if (blankEmployeeNum)
{
alert("Please go back and enter an employee number before submitting.");
event.preventDefault();
}
else if (blankFields)
{
alert("One or more of the fields submitted were blank. Please go back and try again.";
event.preventDefault();
}
});
});
'
There is a script error
Update
alert("One or more of the fields submitted were blank. Please go back and try again.";
to
alert("One or more of the fields submitted were blank. Please go back and try again.");
You are missing the closing bracket.
Please note there are some more script errors too. Please resolve then by checking in console.
I have found out few for you like changeLabel is not a function etc. You really need to work a lot on the script. There are many errors.
You need to call event.preventDefault() at first inside the submit function, otherwise the event bubbles up and the form is submitted.
$("form#theForm").submit(function(event) {
event.preventDefault();

disable submit button on some text field value

This is my html code for form
<form action="add.php" method="post">
<table style="border: 1px solid black;padding:20px;" cellspacing="1px">
</br>
</br>
<tr>
<td>Issue No:</td>
<td>
<input name="issueno" type="text" id="issueno" />
</td>
<td>Issue Date:</td>
<td>
<input name="issuedate" type="date" id="issuedate" />
</td>
</tr>
</br>
</br>
<tr></tr>
<tr>
<td>Item Code:</td>
<td>
<input name="itemcode" type="text" id="itemcode" />
</td>
<td>Description:</td>
<td>
<input name="des" type="text" style="width:250px; height:23px" id="desc" />
</td>
<td>Bal Quantity:</td>
<td>
<input name="bal" type="text" id="bal" />
</td>
</tr>
</br>
<tr>
<td>Issue Quantity:</td>
<td>
<input name="issuequ" type="text" id="issuequ" />
</td>
</tr>
</br>
<tr></tr>
<tr>
<td>Remark:</td>
<td>
<input name="remark" type="text" style="width:250px; height:23px" id="remark" />
</td>
</tr>
</br>
<tr>
<td colspan="6">
<center>
<input type="submit" value="submit">
</center>
</td>
</tr>
</table>
</form>
So I want to disable submit button if issue quantity is more than bal quantity and remain enable if issue quantity is less than bal quantity. And I am getting bal quantity on change of item code from ajax call. So how Do I do it??
<script>
/**
* the submit handler...
*/
function checkBeforeSubmit() {
// build your own condition ... :)
if(CONDITION == false) {
alert("You can not submit...");
}else {
// all is good ? so we submit the form ....
document.myForm.submit();
}
}
</script>
<form name="myForm" action="add.php" method="post">
...
<!-- i have changed the type from submit to button and add a handler to execute basic JavaScript function-->
<input type="button" value="submit" onClick="checkBeforeSubmit();">
</form>
Why not you try yo Add/remove disabled attribute to the submit button on qtty change.
This is my working code...
$('#issuequ').blur(function(){
var issueqty = $(this).val();
var bal = $('#bal').val();
if(issueqty > bal){
$('input[type="submit"]').attr('disabled','disabled');
} else if (issueqty < bal){
$('input[type="submit"]').removeAttr('disabled');
}
});
I am here disabling submit on change of issuequ otherwise remain active.

Form Validation all letters

Hi Please find the below form validation code. I've used html5 input attributes for most of the validation except where i need all letter for the first name and last name. The below cose is what i wrote for first name...but looks like it's not entering the if condition. Can anyone please help
and lemme know where I went wrong.....Thanks Guys!!
<!DOCTYPE html>
<html>
<head>
<script>
function formvalid(){
var uname=document.form1.usrname.value;
var letters=/^[a-zA-Z]+$/;
if (uname.value.match(letters)){
alert("Your details have been saved.Please submit the course fee at the cash counter before 13/12/2014 and collect your id card.The training will start on 23/12/2014 from 10.30am to 4.40 pm");
return true;
}else{
alert("Please Enter a valid Username");
uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="form1">
<h1> Register Online</h1>
<Table>
<tr>
<td>First Name</td>
<td><input type="text" name="usrname" required></td>
</tr>
<tr>
<td> Last Name</td>
<td><input type="text" id="usrname1" required></td>
</tr>
<tr>
<td> Email ID</td>
<td><input type="email" id="mail" pattern="[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td> Roll Number</td>
<td><input type="number" min="1" id="roll" required></td>
</tr>
<tr>
<td>Training Program</td>
<td><select id="sel">
<option value="movie">Select Training</option>
<option value="andro">Android</option>
<option value="java">Java</option>
<option value="C">Robotics</option>
<option value="hack">Ethical Hacking</option>
</select></td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="number" min="1" id="number" required></td>
</tr>
<tr><td>
<Button type="submit" onclick="return formvalid()">Submit</BUTTON></td>
<td><BUTTON type="reset">Reset</BUTTON>
</td></tr>
</table>
</form>
</body>
</html>

Form validation using Jquery focus and blur method

I am trying to do simple form validation by using jQuery. Actually I am try to validate the input boxes on blur and focus. I am just validating first input for now which validate user first name.It is not functioning properly.
Can any please help me?
HTML & JS CODE:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Test
</title>
<style type="text/css">
.showerror{
display:block;
}
.noshowerror{
display:none;
}
.remerr{
display:none;
}
.redborder{
border:#F00 solid 1px;
background-color:yellow;
}
.greenborder {
border:#0F3 solid 1px;
background-color:#6F6;
}
</style>
</head>
<body>
<div style="width:450px">
<div style="float:left">
<table>
<form id="eg">
<tr>
<td>
<label>
Name:
</label>
<td>
<input type="text" id="name" />
</tr>
<tr>
<td>
<label>
Surname:
</label>
<td>
<input type="text" id="surname" />
</tr>
<tr>
<td>
<label>
Email:
</label>
<td>
<input type="text" id="email" />
</tr>
<tr>
<td>
<label>
Number:
</label>
<td>
<input type="text" id="number" />
</tr>
<tr>
<td>
<label>
Age:
</label>
<td>
<input type="text" id="age" />
</tr>
<tr>
<td>
<label>
Comment:
</label>
<td>
<input type="text" id="comment" />
</tr>
<tr>
<td>
<label>
Password
</label>
<td>
<input type="password" id="pwd" />
</tr>
<tr>
<td>
<label>
Confirm Password
</label>
<td>
<input type="password" id="cnfmpwd" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="test" />
</td>
</tr>
</form>
</table>
</div>
<div style="float:right">
<p id="fail" class="noshowerror" >
Please enter name
</p>
<p id="nameerr2" class="remerr">
Name is correct
</p>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
});
$('#name').blur(function () {
var nameRegex = /^[A-Za-z]+$/;
var fname = document.getElementById("name").value;
if (!nameRegex.test(fname)) {
$("#name").addClass('redborder');
} else if (fname == " ") {
$("#name").addClass('redborder');
} else {
$("#name").addClass('greenborder');
return false;
}
});
});
</script>
</body>
</html>
Thanks in advance
I have refined our code and its working as you intended, there were several mistake in defining the elements within table,may be you can have a look at my code on how to define it .
LIVE DEMO
HTML CODE:
<body>
<div style="width:450px">
<div style="float:left">
<form id="eg" action="/">
<table>
<tr>
<td>
<label>Name:</label>
</td>
<td>
<input type="text" id="name" />
</td>
</tr>
<tr>
<td>
<label>Surname:</label>
</td>
<td>
<input type="text" id="surname" />
</td>
</tr>
<tr>
<td>
<label>Email:</label>
</td>
<td>
<input type="text" id="email" />
</td>
</tr>
<tr>
<td>
<label>Number:</label>
</td>
<td>
<input type="text" id="number" />
</td>
</tr>
<tr>
<td>
<label>Age:</label>
</td>
<td>
<input type="text" id="age" />
</td>
</tr>
<tr>
<td>
<label>Comment:</label>
</td>
<td>
<input type="text" id="comment" />
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="password" id="pwd" />
</td>
</tr>
<tr>
<td>
<label>Confirm Password</label>
</td>
<td>
<input type="password" id="cnfmpwd" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="test" onclick="return false;" />
</td>
</tr>
</table>
</form>
</div>
</div>
<div style="float:right">
<p id="fail" class="noshowerror">Please enter name</p>
<p id="nameerr2" class="remerr">Name is correct</p>
</div>
</body>
JS CODE:
$(document).ready(function () {
if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
});
$('#name').blur(function () {
var nameRegex = /^[A-Za-z]+$/;
// var fname = document.getElementById("name").value;
var fname = $("#name").val();
alert(nameRegex.test(fname));
if (!(nameRegex.test(fname))) {
$("#name").removeClass('greenborder').addClass('redborder');
} else if (fname == " ") {
$("#name").removeClass('greenborder').addClass('redborder');
} else {
$("#name").removeClass('redborder').addClass('greenborder');
return false;
}
});
});
When your using jQuery lib, make sure you make the most of it, i have seen that there was raw javascript syntax in your code. jQuery was designed make things easier by reducing the syntax.
Edited:
I have refined the code, so that the code work on any number of times.
Happy Coding :)
$('#name').blur(function(){
trigger the blur event.
To listen for the blur event, made by the user :
$('#name').on("blur", function(){
if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
can be changed by :
<input type="text" name="name" id="name" placeholder="Name Please" />
http://www.w3schools.com/tags/att_input_placeholder.asp
For your issue :
var fname = $("#name").val(); //jQuery style
$('#name').on("blur", function(){
// we want element #name a range of letters
var regexp = /^([A-Za-z])+$/;
// if the element #name contains a range of letters defined in var regexp
if (!nameRegex.test(fname)) {
$("#name").addClass('redborder');
return true;
}
// if the element #name is empty, does not contain string
if ( $("name").length === 0 ) {
$("#name").addClass('redborder');
return true;
}
// if we are still here, means that the element #name is valid
$("#name").addClass('greenborder');
return false;
}
// on focus name input
$("#name").on("focus", function() {
// if the input get the redborder class, then reset
if ( fname.hasClass("redborder") ){
fname.removeClass("redborder");
}
}

Categories

Resources