Need to inject client-side js validation before jquery ajax validation - javascript

I'm having trouble getting my validate(form) function to run "before" my ajax function. Any recommendations on how to tie the two together and have them run in order when the form is submitted would be most helpful.. thanks!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="includes/JSValidation.js"></script>
<script type="text/javascript">
// These first three lines of code compensate for Javascript being turned on and off.
// It simply changes the submit input field from a type of "submit" to a type of "button".
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Contact Us!" />');
$(function() {
$('#contactForm input#submit').click(function() {
$('#contactForm').append('<img src="ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var firstname = $('input#firstname').val();
var lastname = $('input#lastname').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'email.php',
data: 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&message=' + message,
success: function(results) {
$('#contactform img.loaderIcon').fadeOut(1000);
$('td#response').html(results);
}
}); //end ajax
});
});
//Validation
function validate(form){
var firstName = form.firstname.value;
var lastName = form.lastname.value;
var email = form.email.value;
var subject = form.subject.value;
var message = form.message.value;
var errors = [];
if (!reProperName.test(firstName)) {
errors[errors.length] = "You must enter a valid first name.";
}
if (!reProperName.test(lastName)) {
errors[errors.length] = "You must enter a valid last name.";
}
if (!reEmail.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (checkTextArea(message,1000)) {
errors[errors.length] = "Your message is too long. It must be less than 100 characters.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
submitForm(contactForm);
return true;
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body>
<div id="wrap">
<?php
require 'includes/header.php';
?>
<div id="main">
<h1 align="center">Contact Form:</h1>
<div>
<form method="post" id="contactForm" autocomplete="on" onclick="return validate(this);" action="includes/email.php">
<table width="350" border="0" align="center" cellpadding="4" cellspacing="0">
<tr>
<td><label>Your First Name:</label></td>
<td><input type="text" name="firstname" id="firstname" style="width:100%" /> </td>
</tr>
<tr>
<td><label>Your Last Name:</label></td>
<td><input type="text" name="lastname" id="lastname" style="width:100%" /></td>
</tr>
<tr>
<td><label>Your Email:</label></td>
<td><input type="text" name="email" id="email" style="width:100%" /></td>
</tr>
<tr>
<td colspan="2">
<label>Your Message:</label><br /><br />
<textarea name="message" style="width:100%;height:160px" id="message"></textarea>
</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="submit" value="Contact Us!" id="submit"></td>
</tr>
<tr align="center">
<td colspan="2" id="response" />
</tr>
</table>
</form>
</div>
<div class="push" />
</div>
<?php
require 'includes/footer.php';
?>
</body>

Change the validate function as following,
function validate() {
var firstName = $("#firstname").val();
var lastName = $("#lastname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
***************
}
and change the jQuery event,
$(function () {
$('#contactForm #submit').click(function (e) {
e.preventDefault();
if (validate()) {
// Ajax code
}else{
// not valid
}
});
});

Related

Uncaught ReferenceError: validateForm is not defined at HTMLInputElement.onclick

why do I have this problem? I'm trying to get an output to the user name in the site. but it keeps giving me this problem!
I ant it to write me that the user name is not correct when im starting with a number or it is blanked at all- it gives me nothing.
please help me I am sitting on this above an hour:((
Snippet
function validateForm() {
var res = true;
res = userNameVal() && res;
return res;
}
function userNameVal() {
var userName = document.getElementById("username").value;
var msgBox = document.getElementById("userNameCheck");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter user name";
msgBox.style.color = "red"
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "User name must start with a letter ";
msgBox.style.color = "red";
return false;
}
msgBox.innerHTML = "";
return true;
}
<form id="form1" method="post" onsubmit="return validateForm()">
<table class="table3">
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td>
<input type="text"
name="username"
id="username"
onchange="userNameVal()" />
</td>
<td>
<div id="userNameCheck"></div>
</td>
</tr>
<tr>
<td><input type="button"
value="submit"
onclick="return validateForm()"/>
<input type="reset" value="reset" />
</td>
<td></td>
<td></td>
</tr>
</table>
</form>

I just want that my should be highlighted on the form after selecting it the radio button

this is my html code please have a look.
and the below is my js code please help me with highlighting the data.
in this code i reading the data from the xml file and then printing it on the web page using js and then i want to get the selected data by user to be highlited on the form.
in the xml file whole the infromation of the customer has given.
Html Code
<!DOCTYPE html>
<html>
<head>
<title>Client Rental</title>
<link rel="stylesheet" type="text/css" href="classdemo_2.css">
<script type="text/javascript"enter code here src="jsonfilehandler.js"></script>
</head>
<body>
<header><h1>Client Rental Information</h1> <img src="1.png">
</header>
<h2>Search the Client Below</h2>
<table>
<tr><td>Search By Last Name</td><td></td><td></td><td><input type="text" size="30" id="lastname"></td></tr>
</table>
<br>
<h3 id="searchvalue"></h3>
<br>
<table id="searchresults" ></table>
<form id="register" onsubmit="register();return false">
<table class="form">
<tr><td>Last Name</td><td><input type="text" id="lastname" size="15" pattern="[A-Za-z]{1,15}" required="true"></td></tr>
<tr><td>First Name</td><td><input type="text" id="firstname" size="15" pattern="[A-Za-z]{1,15}" required="true"></td></tr>
<tr><td>Address</td><td><input type="text" id="address" size="25" required="true"></td></tr>
<tr><td>Sate_province</td><td><input type="text" id="state" placeholder="state" size="15" required="true"></td></tr>
<tr><td>Email</td><td><input type="email" id="email" placeholder="example#example.com" size="20" required="true"></td></tr>
<tr><td>Phone Number</td><td><input type="phone" id="phone" placeholder="A1A1A1" size="15" required="true"></td></tr>
</table>
<input type="submit" value="Submit">
</form>
<footer class="footer">
Contact information
</footer>
</table>
</body>
</html>
Js Code:-
/*jsonfilehandler.js*/
var xhr = new XMLHttpRequest();
var r;
var index;
window.onload=loaddata;
function loaddata() {
//event listener
document.getElementById("lastname").addEventListener("keyup", function (){ searchFullName(this.value);},false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
r = JSON.parse(xhr.responseText);
//displayData(r);
}
};
xhr.open("GET", "rentalclients.json", true);
xhr.send();
}
function searchFullName(name) {
//var r=JSON.parse(xhr.responseText);
var output=" ";
var searchname;
var displayRadiobuttons= "";
for(var i=0; i<r.length; i++)
{
var obj=r[i];
searchname=obj.last_name;
if(searchname.toLowerCase().startsWith(name))
{
obj=obj.last_name+"\t\t\t\t"+obj.first_name;
displayRadiobuttons+="<input type=radio name=listitem";
displayRadiobuttons += " value=" + i + " ";
displayRadiobuttons+= "onclick=if(this.checked) {setClientObject(searchname)}>";
displayRadiobuttons+=obj+ "<br>";
}
}
document.getElementById("searchresults").innerHTML=displayRadiobuttons;
//displayRadiobuttons= onclick=if(this.checked){setClientObject()};
}
function setClientObject(myname) {
var c=0;
alert(c);
index=i;
var dataitem;
var clientobject = {
lastname,
firstname,
address,
postalcode,
state,
email,
phone
};
var searchname;
for(var i=0; i<r.length; i++)
{
var obj=r[i];
searchname=obj.last_name;
if(searchname.toLowerCase().startsWith(name))
{
clientobject.lastname = document.getElementByTagName("last_name").value;
clientobject.firstname = document.getElementByTagName("first_name").value;
clientobject.address = document.getElementByTagName("address").value;
clientobject.postalcode = document.getElementByTagName("state_prov").value;
clientobject.email = document.getElementByTagName("email").value;
clientobject.phone = document.getElementByTagName("phone").value;
}
}
//input variables into clientobject
document.getElementById("lastname").value = clientobject.lastname;
document.getElementById("firstname").value = clientobject.firstname;
document.getElementById("address").value = clientobject.address;
document.getElementById("state").value = clientobject.state;
document.getElementById("email").value = clientobject.phone;
document.getElementById("phone").value = clientobject.state;
}```
I reformatted the code, but I still don't know what you are trying to accomplish.
<html>
<!DOCTYPE html>
<html>
<head>
<title>Client Rental</title>
<link rel="stylesheet" type="text/css" href="classdemo_2.css">
<script type="text/javascript"enter code here src="jsonfilehandler.js"></script>
</head>
<body>
<header><h1>Client Rental Information</h1> <img src="1.png">
</header>
<h2>Search the Client Below</h2>
<table>
<tr><td>Search By Last Name</td><td></td><td></td><td><input type="text" size="30" id="lastname"></td></tr>
</table>
<br>
<h3 id="searchvalue"></h3>
<br>
<table id="searchresults" ></table>
<form id="register" onsubmit="register();return false">
<table class="form">
<tr><td>Last Name</td><td><input type="text" id="lastname" size="15" pattern="[A-Za-z]{1,15}" required="true"></td></tr>
<tr><td>First Name</td><td><input type="text" id="firstname" size="15" pattern="[A-Za-z]{1,15}" required="true"></td></tr>
<tr><td>Address</td><td><input type="text" id="address" size="25" required="true"></td></tr>
<tr><td>Sate_province</td><td><input type="text" id="state" placeholder="state" size="15" required="true"></td></tr>
<tr><td>Email</td><td><input type="email" id="email" placeholder="example#example.com" size="20" required="true"></td></tr>
<tr><td>Phone Number</td><td><input type="phone" id="phone" placeholder="A1A1A1" size="15" required="true"></td></tr>
</table>
<input type="submit" value="Submit">
</form>
<footer class="footer">
Contact information
</footer>
</table>
</body>
<script>
var xhr = new XMLHttpRequest();
var r;
var index;
window.onload=loaddata;
function loaddata() {
//event listener
document.getElementById("lastname").addEventListener("keyup", function (){ searchFullName(this.value);},false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
r = JSON.parse(xhr.responseText);
//displayData(r);
}
};
xhr.open("GET", "rentalclients.json", true);
xhr.send();
}
function searchFullName(name) {
//var r=JSON.parse(xhr.responseText);
var output=" ";
var searchname;
var displayRadiobuttons= "";
for(var i=0; i<r.length; i++)
{
var obj=r[i];
searchname=obj.last_name;
if(searchname.toLowerCase().startsWith(name))
{
obj=obj.last_name+"\t\t\t\t"+obj.first_name;
displayRadiobuttons+="<input type=radio name=listitem";
displayRadiobuttons += " value=" + i + " ";
displayRadiobuttons+= "onclick=if(this.checked) {setClientObject(searchname)}>";
displayRadiobuttons+=obj+ "<br>";
}
}
document.getElementById("searchresults").innerHTML=displayRadiobuttons;
//displayRadiobuttons= onclick=if(this.checked){setClientObject()};
}
function setClientObject(myname) {
var c=0;
alert(c);
index=i;
var dataitem;
var clientobject = {
lastname,
firstname,
address,
postalcode,
state,
email,
phone
};
var searchname;
for(var i=0; i<r.length; i++)
{
var obj=r[i];
searchname=obj.last_name;
if(searchname.toLowerCase().startsWith(name))
{
clientobject.lastname = document.getElementByTagName("last_name").value;
clientobject.firstname = document.getElementByTagName("first_name").value;
clientobject.address = document.getElementByTagName("address").value;
clientobject.postalcode = document.getElementByTagName("state_prov").value;
clientobject.email = document.getElementByTagName("email").value;
clientobject.phone = document.getElementByTagName("phone").value;
}
}
//input variables into clientobject
document.getElementById("lastname").value = clientobject.lastname;
document.getElementById("firstname").value = clientobject.firstname;
document.getElementById("address").value = clientobject.address;
document.getElementById("state").value = clientobject.state;
document.getElementById("email").value = clientobject.phone;
document.getElementById("phone").value = clientobject.state;
}
</script>
</html>

Delete records from a table (Firebase)

I do not know how to delete the specific record when I click the img on the right
I want it to work like that:
Also I put an img for delete the specific record but I do not know how to add an event listener on img in the JS to delete the row and the record. Also, when I insert data in the DB I add the UID of the specific object for the delete purposes.
HTML code
<html>
<head>
<title>Fall-App Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK rel="stylesheet" href="style.css" type="text/css" media="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
</head>
<body>
<div class="cabecera">
</div>
<div class="cuerpo">
<div class="botones">
<table style="background-color:grey;height:100%; width:99%" border="10" id="logout">
<tr><td>Επεξεργασία Κοινωνικών Υπηρεσιών</td></tr>
<tr><td>Αποσύνδεση</td></tr>
</table>
</div>
<div class="welcome">
<div class="container">
<!--<form>
<input class="input" type="text" id="searchTxt" placeholder="Αναζήτηση για ...">
<input class="submit" type="submit" id="searchBtn" value="Εύρεση">
</form>-->
<input type="text" placeholder="Επιβεβαίωση Κωδικού" name="rePsw" id="rePswReg" required>
<button type="submit" id="searchBtn">Εγγραφή</button>
<table class="searchTable" style="width:100%">
<thead>
<tr>
<td>Name Of Service</td>
<td>Address</td>
<td>Postal</td>
<td>City</td>
<td>Phone</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
<form id="submitForm">
Name Of Service:<br>
<input type="text" name="name" id="nameDB"><br>
Address:<br>
<input type="text" name="address" id="addressDB">
Postal:<br>
<input type="text" name="postal" id="postalDB">
City:<br>
<input type="text" name="city" id="cityDB">
Phone:<br>
<input type="text" name="phone" id="phoneDB">
<button type="submit" id="btnInsert">Inster</button>
</form>
<script src="registered.js"></script>
</div>
</div>
<div class="pie">
</div>
</body>
</html>
JS code
(function() {
//initialize Firebase
var config = {
};
firebase.initializeApp(config);
const searchBtn = document.getElementById('searchBtn');
//const searchTxt = document.getElementById('searchTxt');
var messagesRef2 = firebase.database().ref().child('socialServices');
var counter=-1;
//bring all to the table
var messagesRef2 = firebase.database().ref().child('socialServices');
messagesRef2.on("child_added", snap => {
counter++;
var name=snap.child("name").val();
var address=snap.child("address").val();
var postal=snap.child("postal").val();
var city=snap.child("city").val();
var phone=snap.child("phone").val();
$("#tableBody").append("<tr><td>" + name + "</td><td>" + address + "</td><td>" +
postal + "</td><td>" + city + "</td><td>" + phone + "</td><td>" + "<img src='http://icons.iconarchive.com/icons/hopstarter/button/16/Button-Close-icon.png' id='Img'>" + "</td></tr>");
});
//regerence messages collection
var messagesRef = firebase.database().ref('socialServices');
//listen for form submit
document.getElementById('submitForm').addEventListener('submit', submitForm);
//submit form
function submitForm(e){
e.preventDefault();
//get values
var name=getInputVal('nameDB');
var address=getInputVal('addressDB');
var postal=getInputVal('postalDB');
var city=getInputVal('cityDB');
var phone=getInputVal('phoneDB');
//save message
saveMessage(name, address, postal, city, phone);
}
//function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//save message to firebase
function saveMessage(name, address, postal, city, phone){
var newMessageRef = messagesRef.push();
newMessageRef.set({
id: newMessageRef.key,
name: name,
address: address,
postal: postal,
city: city,
phone: phone
});
}
}());

Jquery .post() not calling script

I am trying to pass the data from a form to an insertion script without having the form data cleared. I am using this function to act on the press of the submit button but I get nothing. It is even set to throw an error if the form is missing data but it doesn't even get that far. I can only assume I am not calling it properly.
$(function() {
$(".submit").click(function() {
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (facility == '' || riskclient == '' || riskdate == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
<div class="body">
<div align='center'>
<div class="tablebackground">
<form method ="post" name= "form" id="form">
<table border='1' >
<tr>
<td>Facility</>
<td><input type="text" name= "riskFacility" id="facility"></td>
<td rowspan='4'><input type="submit" name="submit" value="New Client" class="submit"/</td>
</tr>
<tr>
<td>Client</td>
<td><input required type="text" name="riskClientId" id="riskclient" value="<?php echo htmlspecialchars($_POST['riskClientId']); ?>"></td>
</tr>
<tr>
<td>Audit Date</td><td> <input required type="text" id="datepicker" name="riskauddate" id="riskdate"></td>
</tr>
</table>
</form>
It is definitely not passing anything to the insertion script. So again, I think I am calling it incorrectly.
I see your html tags are not closed properly
<div class="body">
<form method="post" name="form" id="form">
<table border='1'>
<tr>
<td>Facility</td>
<td>
<input type="text" name="riskFacility" id="facility">
</td>
<td rowspan='4'>
<input type="submit" name="submit" value="New Client" class="submit" /> </td>
</tr>
<tr>
<td>Client</td>
<td>
<input required type="text" name="riskClientId" id="riskclient" value="">
</td>
</tr>
<tr>
<td>Audit Date</td>
<td>
<input required type="text" id="datepicker" name="riskauddate" id="riskdate">
</td>
</tr>
</table>
</form>
and check if it comes to error call back
I think it's useful..
$(document).ready(function () {
$('#submit').on('click', function (event) {
event.preventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity='+ facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
or
// var datastring = $("#form").serialize();
if(facility=='' || riskclient=='' || riskdate=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function (msg) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
})
event.preventDefault used to stop submit and page reload.
datastring = $("#form").serialize(); used to submit all data values so no need to take each and every variable assign value.
You can refactor a little the code like this, revise your html tags. You have a double id property in an input, and missing clousure tags.
$(document).ready(function() {
$(".submit").click(function(event) {
event.PreventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (!facility || !riskclient || !riskdate) {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
//send ajax post
}
});
});

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

Categories