External Javascript, CSS not working in Eclipse - javascript

I am a beginner in JS and I have checked that the external js files and css are linked. I have a form as shown below:
The html:
<form id="theForm" action="submitData">
<table>
<tr>
<td>Name:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="name" id ="name" class="Btn"></td>
<td id="nameError" class="red"> </td>
</tr>
<tr>
<td>Contact Number:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="phone" id = "phone" class="Btn"></td>
<td id="phoneError" class="red"> </td>
</tr>
<tr>
<td>Email:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="email" id = "email" class="Btn"></td>
<td id="emailError" class="red"> </td>
</tr>
<tr>
<td>Address:</td>
<td><input style="color: black;" type="text" name="address" class="Btn"></td>
<td>-</td>
</tr>
<tr>
<td>Password:</td>
<td><input style="color: black;" type="text" name="password" class="Btn">
<td>-</td>
</tr>
<tr>
<td></td>
<td>
<input style="color: black;" type="submit" value="SEND" id="submit"/>
</td>
</tr>
</table>
</form>
The CSS here only run a certain portion and not all. The class red does not run at all
The CSS:
//USER ACCOUNT CREATION VALIDATION CSS
.red span{ /* for error messages */
font-style: italic;
color: red;
}
input.error { /* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
td {
margin: 0;
padding: 10px 10px 10px 3px;
}
The JS:
window.onload = init;
// The "onload" handler. Run after the page is fully loaded.
function init() {
// Attach "onsubmit" handler
document.getElementById("theForm").onsubmit = validateForm;
// Set initial focus
document.getElementById("name").focus();
}
function validateForm() {
return (isNotEmpty("name", "Please enter your name!")
&& isNotEmpty("address", "Please enter your address!")
&& isNotEmpty("phone", "Please enter a valid phone number!")
&& isNotEmpty("phone", "Enter 8 digits", 8, 8)
&& isNotEmpty("email", "Enter a valid email!")
);
}
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
document.getElementById("theForm").submit();
In this JS, i want to check if all fields are filled an not empty, but the page does not validate at all. Why is this so?
I would like to find out why did the CSS not show as specified.
EDITED JS
<script>
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var phone = document.forms["myForm"]["phone"].value;
var email = document.forms["myForm"]["email"].value;
var add = document.forms["myForm"]["address"].value;
var passwd = document.forms["myForm"]["password"].value;
if (name == null || name == "" || phone == null || phone == "" || email == null || email == "" || add == null || add == ""
|| passwd == null || passwd == "") {
alert("All must be filled out");
return false;
}
}</script>

Js- You Forgot to give Id's for everything, so nothing is actually being called. (You have names, not IDs)
With Regards to your CSS problem try the following:
span.red {
font-style: italic;
color: red;
}
input.error {
/* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
td {
margin: 0;
padding: 10px 10px 10px 3px;
}
This isn't Javascript you can't comment with // only /**/. Also Note the span.red, this means select spans with the class red. You wrote select spans that are the children of .red
That should Fix it... Oh, one more thing, the action is being called before you are actually validating, You should some how submit that from JS.
Remove the submit from the input, change it to a button, and bind the click event the input[type=submit] becomes <button onclick="validateForm()">Submit</button>
At the end of all validation functions
add this document.getElementById("theForm").submit();
EDIT: Sorry, Looks like you found your JS mistake while I was writing this answer, hope the rest helps though...
EDIT 2: Updated Code
HTML
<form id="theForm" action="submitData">
<table>
<tr>
<td>Name:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="name" id ="name" class="Btn"></td>
<td id="nameError" class="red"> </td>
</tr>
<tr>
<td>Contact Number:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="phone" id = "phone" class="Btn"></td>
<td id="phoneError" class="red"> </td>
</tr>
<tr>
<td>Email:<span class="red">*</span></td>
<td><input style="color: black;" type="text" name="email" id = "email" class="Btn"></td>
<td id="emailError" class="red"> </td>
</tr>
<tr>
<td>Address:</td>
<td><input style="color: black;" type="text" name="address" class="Btn"></td>
<td>-</td>
</tr>
<tr>
<td>Password:</td>
<td><input style="color: black;" type="text" name="password" class="Btn">
<td>-</td>
</tr>
<tr>
<td></td>
<td>
<button id="submit" onclick="validateForm()">Submit</button>
</td>
</tr>
</table>
</form>
CSS:
span.red{ /* for error messages */
font-style: italic;
color: red;
}
input.error { /* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
td {
margin: 0;
padding: 10px 10px 10px 3px;
}
The JS:
window.onload = init;
// The "onload" handler. Run after the page is fully loaded.
function init() {
// Set initial focus
document.getElementById("name").focus();
}
function validateForm() {
var valid = (isNotEmpty("name", "Please enter your name!") &&
isNotEmpty("address", "Please enter your address!") &&
isNotEmpty("phone", "Please enter a valid phone number!") &&
isNotEmpty("phone", "Enter 8 digits", 8, 8) && isNotEmpty(
"email", "Enter a valid email!"));
if (valid) {
document.getElementById("theForm").submit();
}
}
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
EDIT 3: Try this perhaps?
function validateForm() {
var valid = true;
$("input").each(function(e) {
if (valid) {
var value=$(e.target).val();
if (value === undefined || value==="" ) {
valid = false;
alert("All Fields must be filled out");
}
}
});
return valid;
}
Edit 4:
function validateForm() {
var valid = true;
$("input").each(function() {
if (valid) {
var value=$(this).val();
if (value === undefined) {
valid = false;
alert("All Fields must be filled out");
}
}
});
return valid;
}
Edit 5:
function validateForm() {
var valid = true;
$("input").each(function() {
if (valid) {
var value=$(this).val();
if (value === undefined) {
valid = false;
alert("All Fields must be filled out");
}
}
});
return valid;
}
Edit 6:
function validateForm() {
var valid = true;
var ids = ["name", "phone", "email", "address", "password"];
for (var x in ids) {
var value = document.getElementById(ids[x]).value;
if (value === undefined || value === "") {
valid = false;
}
}
if (!valid) {
alert("All must be filled out");
}
}

I'm not sure about your JavaScript problem, but the error with the .red class is that you've set it to only color span elements inside the element with the .red class.It also looks like the input.error is incorrect. I think you want that to be just .error so when you apply that class to the input field it will change.
.red { /* for error messages */
font-style: italic;
color: red;
}
.error { /* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
td {
margin: 0;
padding: 10px 10px 10px 3px;
}

Related

Display an error message next to the input field if input field is blank

I am new to JavaScript and am a bit stuck...
I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.
Unfortunately is doesn't do anything...
Thanks for your help!!
My HTML:
<form name="user_details" method="post" onsubmit="return checkform()">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
My JavaScript:
function checkform() {
var ok = true,
first_name,
surname,
address,
city,
post_code,
email;
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
}
else if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
}
else if (document.getElementById("address").value == "") {
document.getElementById("address").style.borderColor = "red";
$("#error_address").show();
ok = false;
}
else if (document.getElementById("city").value == "") {
document.getElementById("city").style.borderColor = "red";
$("#error_city").show();
ok = false;
}
else if (document.getElementById("post_code").value == "") {
document.getElementById("post_code").style.borderColor = "red";
$("#error_post_code").show();
ok = false;
}
else if (document.getElementById("email").value == "") {
document.getElementById("email").style.borderColor = "red";
$("#error_email").show();
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
document.getElementById("surname").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
document.getElementById("address").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
document.getElementById("city").style.borderColor = "red";
ok = false;
}
else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
document.getElementById("post_code").style.borderColor = "red";
ok = false;
}
else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
else {
return ok;
}
}
My CSS:
#error_first_name {
display: none;
}
#error_surname {
display: none;
}
#error_address {
display: none;
}
#error_city {
display: none;
}
#error_post_code {
display: none;
}
#error_email {
display: none;
}
Apply the return ok in end of the function also
function checkform() {
var ok = true,
first_name,
surname,
address,
city,
post_code,
email;
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
} else if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
} else if (document.getElementById("address").value == "") {
document.getElementById("address").style.borderColor = "red";
$("#error_address").show();
ok = false;
} else if (document.getElementById("city").value == "") {
document.getElementById("city").style.borderColor = "red";
$("#error_city").show();
ok = false;
} else if (document.getElementById("post_code").value == "") {
document.getElementById("post_code").style.borderColor = "red";
$("#error_post_code").show();
ok = false;
} else if (document.getElementById("email").value == "") {
document.getElementById("email").style.borderColor = "red";
$("#error_email").show();
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
document.getElementById("surname").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
document.getElementById("address").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
document.getElementById("city").style.borderColor = "red";
ok = false;
} else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
document.getElementById("post_code").style.borderColor = "red";
ok = false;
} else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
} else {
return ok;
}
return ok;
}
#error_first_name {
display: none;
}
#error_surname {
display: none;
}
#error_address {
display: none;
}
#error_city {
display: none;
}
#error_post_code {
display: none;
}
#error_email {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform()">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
I want to highlight some points based on your code
The errors is because you didn't include a jquery version in your code.
If you are using jquery then short your code using it.
Don't repeat same property to each id in CSS use a class instead.
Check empty and regex in single condition using ||
function checkform() {
var ok = true,
first_name = $.trim($("#first_name").val()),
surname = $.trim($("#surname").val()),
address = $.trim($("#first_name").val()),
city = $.trim($("#city").val()),
post_code = $.trim($("#post_code").val()),
email = $.trim($("#email").val());
$('input.bdred').removeClass('bdred');
$('.errors').hide();
if (!first_name || !/^[A-Za-z]+$/.test(first_name)) {
$("#first_name").addClass('bdred');
$("#error_first_name").show();
ok = false;
} else if (!surname || !/^[A-Za-z]+$/.test(surname)) {
$("#surname").addClass('bdred');
$("#error_surname").show();
ok = false;
} else if (!address || !/^[A-Za-z]+$/.test(address)) {
$("#address").addClass('bdred');
$("#error_address").show();
ok = false;
} else if (!city || !/^[A-Za-z][0-9]+$/.test(city)) {
$("#city").addClass('bdred');
$("#error_city").show();
ok = false;
} else if (!post_code || !/^[0-9]+$/.test(post_code)) {
$("#post_code").addClass('bdred');
$("#error_post_code").show();
ok = false;
} else if (!email || !/\S+#\S+/.test(email)) {
$("#email").addClass('bdred');
$("#error_email").show();
ok = false;
}
return ok;
}
.errors {
display: none;
}
.bdred {
border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform();">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name" class="errors">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname" class="errors">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address" class="errors">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city" class="errors">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code" class="errors">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email" class="errors">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
You have several issues in your code and you can improve it in many factors, see below.
You don't close the function checkform() properly, you're missing a closing bracket.
You want to return ok from the function no matter what, so you should omit the else block, for example:
function checkform() {
var ok = true,
[ omitted for brevity ]
else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
return ok;
}
You probably want to check all the errors at form submit. Currently what your code does is look for errors in each field and when it encounters one it will display the error message and stop looking for other errors. To change it you should give up else if in favor of just series of if, like so:
function checkform() {
var ok = true,
[ omitted for brevity ]
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
} // See here - it will check each field no matter what
if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
}
return ok;
}
You are not resetting field style if the error is gone. For example - user tries to submit an empty form, so all fields signal an error. Then the user fills just first name and submits, but the error is still shown, because you never reset it. You could add an else to each check and act accordingly.
You should use === for string comparison (see this answer)
I see you are using jQuery, you should not mix "bare" js (like document.getElementById with jQuery code, because it makes the code messy. With jQuery you can get value of a field like so: $('<css selector here>').val(), for example $('#first_name').val() and you can change styles, by doing $('<css selector>').css('<property', '<value>')
You should not mix presentation and code (like setting styles) instead add and remove a css class and style it in your stylesheet. You can add class with jQuery like so: $('<css selector').addClass('<you class name') and remove it analogically $('<css selector').removeClass('<you class name')
You should attach your event handlers (like onsubmit) in your script file, so you don't clutter your HTML with event handlers and JS with a lot of functions called only from HTML. This improves readability of your code. You can attach your event handler in jQuery like so:
$(function() { // This wait's for document.ready.
// It's required to attach event in script
// because scripts are ran before browser parses HTML
$('#formId').submit(function() {
return false; // This gets called on form submit
});
});
I've created a plunker that demonstrates all of my points
For more information you should see jQuery website and other questions at stackoverflow.
If you used jquery ,you can shorten your code with making array for same pattern group and using .each
function checkform() {
var ok = true;
var character = [["first_name","surname","address"],["/^[A-Za-z]+$/"]];
var city = [["city"],["/^[A-Za-z][0-9]+$/"]];
var post = [["post_code"],["/^[0-9]+$/"]];
var email = [["email"],["/\S+#\S+/"]];
$("form[name='user_details'] input").each(function(){
if($.inArray(this.id,character[0]) >= 0 ) {
ok = showError(this,character[1]);
} else if(this.id == city[0]) {
ok = showError(this,city[1]);
} else if(this.id == post[0]) {
ok = showError(this,post[1]);
} else if(this.id == email[0]) {
ok = showError(this,email[1]);
}
});
return ok;
}
function showError(t,p) {
if(t.value == "" || !p.test(t.value)){
$(t).css("borderColor","red");
$("#error_"+t.id).show();
return false;
}
return true;
}

How to check the table whether the same roll number exists or not using javascript

Can we can check the roll number already exists or not.
with javascript
can we validate this
Showing with a alert message that the roll number exists if it is
already in the table
.
window.onload = function() {
document.getElementById('new').style.display = 'none';
};
function addtable(){
document.getElementById('new').style.display = 'block';
Rollno = document.getElementById("roll_number");
Name = document.getElementById("student_name");
Class = document.getElementById("class");
var Gender = null;
var inputElements = document.getElementsByClassName('gender');
for (var i = 0; inputElements[i]; ++i) {
if(inputElements[i].checked){
Gender = inputElements[i].value;
break;
}
};
Age = document.getElementById("age");
Phone = document.getElementById("phone_number");
var Result = null;
var inputElements = document.getElementsByClassName('result');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
Result = inputElements[i].value;
break;
}
};
var table = document.getElementById("new");
rowCount = table.rows.length;
row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= Rollno.value;
row.insertCell(1).innerHTML= Name.value;
row.insertCell(2).innerHTML= Class.value;
row.insertCell(3).innerHTML= Gender;
row.insertCell(4).innerHTML= Age.value;
row.insertCell(5).innerHTML= Phone.value;
row.insertCell(6).innerHTML= Result;
row.insertCell(7).innerHTML='<input type="submit" value = "Delete" onclick="deleteRow(this)">';
var roll = document.forms["student_detail"]["roll_number"].value;
if (roll == "") {
alert("Rollno must be filled out");
return false;
}
var name = document.forms["student_detail"]["student_name"].value;
if (name == ""){
alert("Name must be filled out");
return false;
}
var clas = document.forms["student_detail"]["class"].value;
if (clas == "") {
alert("select the class");
return false;
}
var age = document.forms["student_detail"]["age"].value;
if (age == ""){
alert("Age must be filled out");
return false;
}
var phone = document.forms["student_detail"]["phone_number"].value;
if (phone == "") {
alert("Phone number must be filled out");
return false;
}
if (document.student_detail.result1.checked == true && document.student_detail.result2.checked == true){
alert('Select any one result');
return false ;
}
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("new");
table.deleteRow(index);
}
function myFunction() {
var x = document.getElementById('myTable');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var change = document.getElementById("toggle");
if (change.innerHTML === "Hide Form")
{
change.innerHTML = "Show Form";
}
else {
change.innerHTML = "Hide Form";
}
}
function hideElem(){
document.getElementById('new').style.visibility = "hidden";
}
function showElem(){
document.getElementById('new').style.visibility = "visible";
}
.abc table{
width: 100%;
border-collapse: collapse;
}
.abc table th{
border: 1px solid #000;
}
.abc table td{
border: 1px solid #000;
}
h2{
color: black;
text-shadow: 2px 2px 8px #FF0000
}
input[type=text],select,input[type=number]{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 2px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=button] {
width: 50%;
background-color: #4CAF50;
color: white;
padding: 14px 10px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=button]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<form name="student_detail" method="post" action="#" onsubmit="return addtable();">
<table id="myTable" >
<tr>
<td><h2>School Management Application</h2></td>
</tr>
<tr>
<td><label for="roll_number">Roll no</label></td>
<td><input type="text" id="roll_number" name="roll_number" placeholder="Roll Number"></td>
</tr>
<tr>
<td><label for="student_name">Student name</label></td>
<td><input type="text" id="student_name" name="student_name" placeholder="Student Name"></td>
</tr>
<tr>
<td><label for="class">Class</label></td>
<td><select name="class" id="class">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select></td>
</tr>
<tr>
<td><label>Gender</label></td>
<td><input type="radio" class="gender" name="gender" value="male">Male
<input type="radio" class="gender" name="gender" value="female">Female</td>
</tr>
<tr>
<td><label for="age">Age</label></td>
<td><input type="number" id="age" name="age" placeholder="Age"></td>
</tr>
<tr>
<td><label for="phone_number">Phone number</label></td>
<td><input type="text" id="phone_number" name="phone_number" placeholder="Phone Number"></td>
</tr>
<tr>
<td><label>Result</label></td>
<td><input type="checkbox" class="result" name="result1" value="passed" >Passed
<input type="checkbox" class="result" name="result2" value="failed" />Failed</td>
</tr>
<tr>
<td><input type="button" value="Submit" onclick="addtable()"></td>
</tr>
</table>
</form>
<table>
<tr>
<td><input type="button" value="Hide Form" id="toggle" onclick="myFunction()">
<input type="button" value="Hide table" id="tab" onclick="hideElem()">
<input type="button" value="Show table" id="tab1" onclick="showElem()"></td>
</tr>
</table>
<div class="abc">
<table id="new">
<tr>
<th>Rollno</th>
<th>Student name</th>
<th>Class</th>
<th>Gender</th>
<th>Age</th>
<th>Phone number</th>
<th>Result</th>
</tr>
</table>
</div>
Need to get alert if the same roll number enters again.After
submiting And a alert message to be shown
Can any one help me to do this
Here's a function that checks for duplicates
checkDupes($("#someId"));
function checkDupes(itemArray) {
var isdupe = false;
for (var i = itemArray.length - 1; i >= 0; i--) {
var value = itemArray[i].value;
if (value == null || value == '' || value.trim().length == 0) {
itemArray[i].style.backgroundColor = 'red';
} else {
if (i > 0) {
for (var j = i - 1; j > -1 && i > 0; j--) {
if (value.trim().toLowerCase() == itemArray[j].value.trim().toLowerCase()) {
itemArray[i].style.backgroundColor = 'red';
isdupe = true;
}
}
if (!isdupe) {
itemArray[i].style.backgroundColor = 'transparent';
}
}
}
}
}

Using JavaScript to Open iFrame form success in parent window

We are currently using JavaScript to process our forms, but the form is contained in an iFrame, which opens the success result URL in the iFrame. We would like the success result (once form is filled in) to point to the parent frame...
Script for form:
<script>try
{
var lastSubmission = null;
var ContactId = 0; var _wow;
var CaptureId = 12;
var PageId = 0;
var EmailId = 0;
var CampaignName = '';
var IsNewContact = false;
var IsTest = false;
var IsUserValid;
var gatorLeadsTrackingOptions = 0;
}catch(e){}
errorMessage.innerHTML ='';
successMessage.innerHTML ='';
function GatorTrim(x) { return x.replace(/^\s+|\s+$/gm,'');};function CaptureFormData()
{
if(lastSubmission != null){
secondsSinceLastSubmission = (new Date().getTime() - lastSubmission) / 1000
if(secondsSinceLastSubmission < 1) {
return;
}
}
var Value;
var CheckSelection = false;
var result;
var ButtonId = 6;
var submissionData = {
captureId: CaptureId,
buttonId: ButtonId,
pageId: PageId,
emailId: EmailId,
campaignName: CampaignName,
contactId: ContactId,
isTest: IsTest,
sendNotificationEmail: false,
passGatorLeadsTrackingDataInRedirectUrl: true,
onlyOneEntry: false,
displayName: 'Volo Not got a code',
emailAddress: '',
values: [],
gatorLeadsTrackingOptions: gatorLeadsTrackingOptions
};
document.getElementById('CaptureControlButton_6_').disabled = true;
document.getElementById('CaptureControlButton_6_').value = 'Submitting, please wait';
setTimeout(function() {try{errorMessage.innerHTML = '';
successMessage.innerHTML = '';
Value = getObject('CaptureControl_4_').value;
if(Value==''){errorMessage.innerHTML += 'The email address field is missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
Value = getObject('CaptureControl_5_').value;
if(Value==''){errorMessage.innerHTML += 'Mandatory fields missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
Value = getObject('CaptureControl_3_').value;
if(Value==''){errorMessage.innerHTML += 'The field name company name is missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
if(errorMessage.innerHTML != ''){return;}
Value = GatorTrim(getObject('CaptureControl_4_').value);
submissionData.emailAddress = Value;
Value = GatorTrim(getObject('CaptureControl_5_').value);
if (Value != undefined) {submissionData.values.push({controlId: 5, value: Value });
}
Value = GatorTrim(getObject('CaptureControl_6_').value);
if (Value != undefined) {submissionData.values.push({controlId: 6, value: Value });
}
Value = GatorTrim(getObject('CaptureControl_3_').value);
if (Value != undefined) {submissionData.values.push({controlId: 3, value: Value });
}
var result = WebCapture.Submit(JSON.stringify(submissionData));
var response = JSON.parse(result.value);
if(response.success==false){errorMessage.innerHTML = 'You have already submitted.';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
return;}
trackingData = response.trackingData;
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
successMessage.innerHTML = 'Thank you for submitting ';
if(typeof _wow != 'undefined' && response.trackWowSubmit){
trackUrlInWow(response.wowUrl);}
var submitRedirectUrl = 'http://takeflight.volocommerce.com/multichannel-selling/'
if(submitRedirectUrl.indexOf('?') == -1){
submitRedirectUrl = submitRedirectUrl + '?';
}else{
submitRedirectUrl = submitRedirectUrl + '&';
}
submitRedirectUrl += 'gator_td=' + trackingData;
window.location.href=submitRedirectUrl;
}catch(e){if(IsTest) { alert(e.message); } else { alert('An error has occurred submitting the data. Please try again.'); }
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
lastSubmission = new Date().getTime();
}, 100);
}</script>
The form (contained in an iframe on our page)
<style>
body {
background: #fff;
color:#000;
font-family: ‘open sans’, sans-serif;
}
input[type=text], input[type=button] {
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 5px;
height: 40px;
border: 1px solid #f1f1f1;
}
input[type=button] {
background-color: #F04D1D;
height: 45px;
font-weight: bold;
color: #FFF;
font-size: 16px;
}
</style>
<table style="width: 300px; background-color: rgb(255, 255, 255);"><base target="_parent" />
<tbody>
<tr>
<td style="text-align: center;"><font color="#f04d1d"><strong><span style="font-family: '‘open sans’', sans-serif, ';'; font-size: 24px;">GET YOUR CODE </span></strong></font></td>
</tr>
<tr>
<td><span style="color: rgb(242, 242, 242);"> </span></td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td>
<table>
<tbody>
<tr>
<td>First Name* </td>
<td><span style="color: rgb(0, 0, 0);">Last Name*</span></td>
</tr>
<tr>
<td><input name="First Name" id="CaptureControl_5_" type="text" value=""></td>
<td><input name="Last Name" id="CaptureControl_6_" type="text" value=""></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 0);">Company Name*</span></td>
</tr>
<tr>
<td><input name="Company Name" id="CaptureControl_3_" type="text" value="" style="width: 300px;"></td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 0);">Your Email*</span></td>
</tr>
<tr>
<td><input name="Email Address" id="CaptureControl_4_" type="text" value="" style="width: 300px;"><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(242, 242, 242);"> </span></td>
</tr>
<tr>
<td><input id="CaptureControlButton_6_" type="button" value="Send" onclick="try{CaptureFormData(0);}catch(e){}" style="width: 300px;"><br>
<div id="errorMessage" style="width:135;height:10;font-family:Verdana;font-size:8pt;color:red;">Error Message Area</div>
<div id="successMessage" style="width:135;height:10;font-family:Verdana;font-size:8pt;color:#000000;">Success Message Area</div>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0); font-size: 10px;"><em>*Required field</em></span></td>
</tr>
</tbody>
</table>
<br>
<br>
Note The form is on a different URL/domain to our main website, where the content is held.
Just use window.top.location to change whole page not only iframe part.

onclick button needs to open in parent window

We have a form on our Marketing Automation (3rd party) software, which is being called on a microsite in an iframe... However, it's currently opening the link in the iframe and not the parent window... I think I know how to fix it, but I want to double check with you guys that the onclick code would work before I pass it over to the marketing company.
I'm using the following code:
<style>
body {
background: #fff;
color:#000;
font-family: ‘open sans’, sans-serif;
}
input[type=text], input[type=button] {
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 5px;
height: 40px;
border: 1px solid #f1f1f1;
}
input[type=button] {
background-color: #F04D1D;
height: 45px;
font-weight: bold;
color: #FFF;
font-size: 16px;
}
</style>
<table style="width: 300px; background-color: rgb(255, 255, 255);">
<tbody>
<tr>
<td style="text-align: center;"><font color="#f04d1d"><strong><span style="font-family: '‘open sans’', sans-serif, ';'; font-size: 24px;">GET YOUR CODE </span></strong></font></td>
</tr>
<tr>
<td><span style="color: rgb(242, 242, 242);"> </span></td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td>
<table>
<tbody>
<tr>
<td>First Name* </td>
<td><span style="color: rgb(0, 0, 0);">Last Name*</span></td>
</tr>
<tr>
<td><input name="First Name" id="CaptureControl_5_" type="text" value=""></td>
<td><input name="Last Name" id="CaptureControl_6_" type="text" value=""></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 0);">Company Name*</span></td>
</tr>
<tr>
<td><input name="Company Name" id="CaptureControl_3_" type="text" value="" style="width: 300px;"></td>
</tr>
<tr>
<td><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 0);">Your Email*</span></td>
</tr>
<tr>
<td><input name="Email Address" id="CaptureControl_4_" type="text" value="" style="width: 300px;"><br>
</td>
</tr>
<tr>
<td><span style="color: rgb(242, 242, 242);"> </span></td>
</tr>
<tr>
<td><input id="CaptureControlButton_6_" type="button" value="Send" target="_parent" onclick="try{CaptureFormData(0);}catch(e){}" style="width: 300px;"><br>
<div id="errorMessage" style="width:135;height:10;font-family:Verdana;font-size:8pt;color:red;">Error Message Area</div>
<div id="successMessage" style="width:135;height:10;font-family:Verdana;font-size:8pt;color:#000000;">Success Message Area</div>
</td>
</tr>
<tr>
<td><span style="color: rgb(0, 0, 0); font-size: 10px;"><em>*Required field</em></span></td>
</tr>
</tbody>
</table>
<br>
<br>
This is the line of code which I want to trigger the successful result to open in the parent window:
<td><input id="CaptureControlButton_6_" type="button" value="Send" target="_parent" onclick="try{CaptureFormData(0);}catch(e){}" style="width: 300px;"><br>
I added Target="_parent" but this failed to open in the parent window... Which makes me think this bit:
onclick="try{CaptureFormData(0);}catch(e){}"
needs to contain something like:
onclick="parent.window.open(try{CaptureFormData(0);}catch(e){})"
Would this solve my problem?
Just to add - the Script for the form is here:
<script>try
{
var lastSubmission = null;
var ContactId = 0; var _wow;
var CaptureId = 12;
var PageId = 0;
var EmailId = 0;
var CampaignName = '';
var IsNewContact = false;
var IsTest = false;
var IsUserValid;
var gatorLeadsTrackingOptions = 0;
}catch(e){}
errorMessage.innerHTML ='';
successMessage.innerHTML ='';
function GatorTrim(x) { return x.replace(/^\s+|\s+$/gm,'');};function CaptureFormData()
{
if(lastSubmission != null){
secondsSinceLastSubmission = (new Date().getTime() - lastSubmission) / 1000
if(secondsSinceLastSubmission < 1) {
return;
}
}
var Value;
var CheckSelection = false;
var result;
var ButtonId = 6;
var submissionData = {
captureId: CaptureId,
buttonId: ButtonId,
pageId: PageId,
emailId: EmailId,
campaignName: CampaignName,
contactId: ContactId,
isTest: IsTest,
sendNotificationEmail: false,
passGatorLeadsTrackingDataInRedirectUrl: true,
onlyOneEntry: false,
displayName: 'Volo Not got a code',
emailAddress: '',
values: [],
gatorLeadsTrackingOptions: gatorLeadsTrackingOptions
};
document.getElementById('CaptureControlButton_6_').disabled = true;
document.getElementById('CaptureControlButton_6_').value = 'Submitting, please wait';
setTimeout(function() {try{errorMessage.innerHTML = '';
successMessage.innerHTML = '';
Value = getObject('CaptureControl_4_').value;
if(Value==''){errorMessage.innerHTML += 'The email address field is missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
Value = getObject('CaptureControl_5_').value;
if(Value==''){errorMessage.innerHTML += 'Mandatory fields missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
Value = getObject('CaptureControl_3_').value;
if(Value==''){errorMessage.innerHTML += 'The field name company name is missing<br>';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
if(errorMessage.innerHTML != ''){return;}
Value = GatorTrim(getObject('CaptureControl_4_').value);
submissionData.emailAddress = Value;
Value = GatorTrim(getObject('CaptureControl_5_').value);
if (Value != undefined) {submissionData.values.push({controlId: 5, value: Value });
}
Value = GatorTrim(getObject('CaptureControl_6_').value);
if (Value != undefined) {submissionData.values.push({controlId: 6, value: Value });
}
Value = GatorTrim(getObject('CaptureControl_3_').value);
if (Value != undefined) {submissionData.values.push({controlId: 3, value: Value });
}
var result = WebCapture.Submit(JSON.stringify(submissionData));
var response = JSON.parse(result.value);
if(response.success==false){errorMessage.innerHTML = 'You have already submitted.';
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
return;}
trackingData = response.trackingData;
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
successMessage.innerHTML = 'Thank you for submitting ';
if(typeof _wow != 'undefined' && response.trackWowSubmit){
trackUrlInWow(response.wowUrl);}
var submitRedirectUrl = 'http://takeflight.volocommerce.com/multichannel-selling/'
if(submitRedirectUrl.indexOf('?') == -1){
submitRedirectUrl = submitRedirectUrl + '?';
}else{
submitRedirectUrl = submitRedirectUrl + '&';
}
submitRedirectUrl += 'gator_td=' + trackingData;
window.location.href=submitRedirectUrl;
}catch(e){if(IsTest) { alert(e.message); } else { alert('An error has occurred submitting the data. Please try again.'); }
document.getElementById('CaptureControlButton_6_').disabled = false;
document.getElementById('CaptureControlButton_6_').value = 'Send';
}
lastSubmission = new Date().getTime();
}, 100);
}</script>
The actual change of the location happens inside your javascript, pretty much at the end:
window.location.href=submitRedirectUrl;
To do that in the topmost frame (i.e. the enveloping page) change it to
window.top.location.href = submitRedirectUrl;
Note that this will only work if both the parent page and the page inside the iframe come from the same domain, because of same-origin-policy
I got around this by redirecting the form to a php script on the same domain which then forwarded to the page intended (on the same domain) to open in the parent window.

Regular Expression not working - Online form validation and submission

So Im having trouble with my form. There are numurous validation techniques set up.
Two of my most obvious problems are an alert that pops upen at the start of the program but should only pop up if an onblur() is activated and my update() function returns a false value.
And aswell, my regular Expressions insist on providing me with false condition when I test them against my strings.
The finished form should validate various information and update values placed in the expenses inputs.
Really stuck on this...
window.onload = initPage;
/*initPage()
Initializes the contents of the Web page */
function initPage() {
//declare array variable dataFields points to input elements from the expenseEntry class
var dataFields = new Array();
var allElems = document.getElementsByTagName("*");
for( var i = 0; i < allElems.length; i ++) {
if(allElems[i].className == "expenseEntry") dataFields.push(allElems[i]);
}
//add onblur event that runs update() function whenever focus leaves a datafield.
for(var i = 0; i < dataFields.length; i++) {
dataFields[i].onblur = update();
}
//event handler that runs validateForm() upon submitting the form.
document.forms[0].onsubmit = validateForm;
}
/* testLength()
Tests a field for its length. */
function testLength(field) {
if (field.value.length == 0) {
// Change the background color to white or yellow depending on the lenght.
field.style.backgroundColor = "yellow";
return false;
}
else field.style.backgroundColor = "white";
return true;
}
/* testPattern()
Tests a field for its pattern. */
function testPattern(field, regx) {
if (regx.test(field)) {
field.style.backgroundColor = "white";
field.style.color = "black";
return true;
}
else field.style.backgroundColor = "yellow";
field.style.color = "red";
return false;
}
/* validateForm()
Validates a Web form */
function validateForm() {
var isValid = true;
//testLength function with lname field also for fname, address, and summary to make sure an entry has been made.
if (testLength(document.forms[0].lname) == false) {
isValid = false;}
if (testLength(document.forms[0].fname) == false) {
isValid = false;}
if (testLength(document.forms[0].address) == false) {
isValid = false;}
if (testLength(document.forms[0].summary) == false) {
isValid = false;}
//must match ACT followed by six digits
if (testPattern(document.forms[0].account,/^ACT\d{6}$/) == false)
{isValid = false;}
//dept field. regx should match DEPT followed by three digits
if (testPattern(document.forms[0].department.value,/^DEPT\d{3}$/) == false)
{isValid = false;}
//Project field with regx should match PROJ followed by five digits
if (testPattern(document.forms[0].project,/^PROJ\d{5}$/) == false)
{isValid = false;}
//call testPattern function to test SSN. match 9 digits or text string
if (testPattern(document.forms[0].ssn,/^\d{3}-\d{2}-\d{4}$/) == false)
{isValid = false;}
if (isValid == false)
{alert("Please fill out all required fields in the proper format.");}
return isValid;
}
/* calcRow
Calculates the costs within one row of the travel report */
function calcRow(row) {
var travel = parseFloat(document.forms[0].elements["travel"+row].value);
var lodge = parseFloat(document.forms[0].elements["lodge"+row].value);
var meal = parseFloat(document.forms[0].elements["meal"+row].value);
return travel+lodge+meal;
}
/* calcTotal()
Calculates the total cost of the travel */
function calcTotal() {
//create a variable totalEXP
var totalExp = 0;
//create a for loop that runs 1 t0 4
for (var i = 1; i <= 4; i++)
// increase the value of totalExp by value returned for calcRow
{ totalExp += calcRow(i);}
return totalExp;
}
/* upDate()
Updates the total travel cost */
function update() {
//create a variable numRegExp
var numRegExp = /^\d*(\.\d{0,2})?$/;
// Test weather the currently selected object matches the numRegExp pattern
if (numRegExp.test(this.value)){
// Display the value of the current object to 2 decimal places.
parseInt(this.value).toFixed(2);
//insert a for loop that runs 1 to 4 for all the expense rows in the form
for (var i = 1; i < 4; i++) {
//Set the value of sub[i] field to the value returned by calcRow()
document.forms[0].elements["sub" + i].value = calcRow(i).toFixed(2);
//set the value of the total field equal to the value returned by the calTotal() function
document.forms[0].total.value = calcTotal().toFixed(2);
}
}
//if the condition is not met display alert and change value.
else if (numRegExp.test(this.value) == false) {
alert("Invalid currency value");
(this.value = "0.00");
this.focus();
}
}
body {background: white url(back.jpg) repeat-y scroll 0px 0px}
#links {position: absolute; top: 10px; left: 0px}
#main {border: 1px solid black; width: 640px; padding: 5px;
background-color: white; margin-left: 100px; margin-top: 0px}
span {color: red; font-family: Arial, Helvetica, sans-serif; font-size: 9pt}
table {font-size: 8pt; width: 630px; margin-top: 5px; margin-bottom: 0px}
th {background-color: rgb(153,204,255); text-align: left; font-weight: normal;
font-family: Arial, Helvetica, sans-serif}
#reporttitle {background-color: white; text-align: center; font-family: Arial, Helvetica, sans-serif;
font-size: 18pt; color: rgb(153,204,255); font-weight: bold}
input {width: 100%; font-size: 8pt}
select {width: 100%; font-size: 8pt}
#lname, #fname {width: 150px}
#account, #department, #project {width: 150px}
#traveltable th {text-align: center}
#subhead {width: 100px}
#travelexphead, #lodgeexphead, #mealexphead {width: 80px}
#date1, #date2, #date3, #date4 {text-align: center}
#travel1, #travel2, #travel3, #travel4 {text-align: right}
#lodge1, #lodge2, #lodge3, #lodge4 {text-align: right}
#meal1, #meal2, #meal3, #meal4 {text-align: right}
#sub1, #sub2, #sub3, #sub4,#total {text-align: right}
#traveltable #totalhead {text-align: right}
textarea {height: 100px; width: 100%}
#main #psub {text-align: center}
#main p input {width: 190px; background-color: rgb(153,204,255); color: black;
letter-spacing: 5}
<?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">
<head>
<!--
New Perspectives on JavaScript, 2nd Edition
Tutorial 5
Case Problem 2
Expense Report Form
Author: Gavin Macken
Date: 8 March `15
Filename: exp.htm
Supporting files: back.jpg, exp.css, links.jpg, logo.jpg, report.js
-->
<title>Expense Report</title>
<link href="exp.css" rel="stylesheet" type="text/css" />
<script src = "report.js" type = "text/javascript"></script>
</head>
<body>
<form id="expform" method="post" action="done.htm">
<div id="links"><img src="links.jpg" alt="" /></div>
<div id="main">
<p><img src="logo.jpg" alt="DeLong Enterprises" /></p>
<table cellspacing="2">
<tr>
<th colspan="5" id="reporttitle">Travel Expense Report</th>
</tr>
<tr>
<th>Name (Last)<span>*</span></th>
<th>(First)<span>*</span></th>
<th>(Initial)</th>
<th>Account<span>*</span></th>
<td><input name="account" id="account" /></td>
</tr>
<tr>
<td><input name="lname" id="lname"/></td>
<td><input name="fname" id="fname"/></td>
<td><input name="init" id="init"/></td>
<th>Department<span>*</span></th>
<td><input name="department" id="department" /></td>
</tr>
<tr>
<th>Social Security Number<span>*</span></th>
<td colspan="2"><input name="ssn" id="ssn" /></td>
<th>Project<span>*</span></th>
<td><input name="project" id="project" /></td>
</tr>
</table>
<table cellspacing="2">
<tr>
<th>Send Check to:<span>*</span></th>
<th>Trip Summary<span>*</span></th>
</tr>
<tr>
<td>
<textarea id="address" name="address" rows="" cols=""></textarea>
</td>
<td>
<textarea id="summary" name="summary" rows="" cols=""></textarea>
</td>
</tr>
</table>
<table id="traveltable" cellspacing="2">
<tr>
<th id="datehead">Travel Date</th>
<th id="travelexphead">Travel Cost</th>
<th id="traveltypehead">Type</th>
<th id="lodgeexphead">Lodging</th>
<th id="mealexphead">Meals</th>
<th id="subhead">Total</th>
</tr>
<tr>
<td><input name="date1" id="date1" /></td>
<td><input name="travel1" id="travel1" value="0.00" class="expenseEntry" /></td>
<td><select name="traveltype1" id="traveltype1">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td><input name="lodge1" id="lodge1" value="0.00" class="expenseEntry" /></td>
<td><input name="meal1" id="meal1" value="0.00" class="expenseEntry" /></td>
<td><input name="sub1" id="sub1" value="0.00" readonly="readonly" /></td>
</tr>
<tr>
<td><input name="date2" id="date2" /></td>
<td><input name="travel2" id="travel2" value="0.00" class="expenseEntry" /></td>
<td><select name="traveltype2" id="traveltype2">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td><input name="lodge2" id="lodge2" value="0.00" class="expenseEntry" /></td>
<td><input name="meal2" id="meal2" value="0.00" class="expenseEntry" /></td>
<td><input name="sub2" id="sub2" value="0.00" readonly="readonly" /></td>
</tr>
<tr>
<td><input name="date3" id="date3" /></td>
<td><input name="travel3" id="travel3" value="0.00" class="expenseEntry" /></td>
<td><select name="traveltype3" id="traveltype3">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td><input name="lodge3" id="lodge3" value="0.00" class="expenseEntry" /></td>
<td><input name="meal3" id="meal3" value="0.00" class="expenseEntry" /></td>
<td><input name="sub3" id="sub3" value="0.00" readonly="readonly" /></td>
</tr>
<tr>
<td><input name="date4" id="date4" /></td>
<td><input name="travel4" id="travel4" value="0.00" class="expenseEntry" /></td>
<td><select name="traveltype4" id="traveltype4">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td><input name="lodge4" id="lodge4" value="0.00" class="expenseEntry" /></td>
<td><input name="meal4" id="meal4" value="0.00" class="expenseEntry" /></td>
<td><input name="sub4" id="sub4" value="0.00" readonly="readonly" /></td>
</tr>
<tr>
<th colspan="5" id="totalhead">TOTAL</th>
<td><input id="total" name="total" readonly="readonly" value="0.00" /></td>
</tr>
<tr>
<td colspan="6"><span>* - Indicates a required field</span></td>
</tr>
</table>
<p id="psub">
<input type="submit" value="Submit Report" />
</p>
</div>
</form>
</body>
</html>
You're testing the DOM element against the regexp, which doesn't make sense. The argument to regx.test() must be a string. You need to use the value of the field:
if (regx.test(field.value)) {
You're setting the onblur property wrong. It should be set to the update function, but you're calling the function at that time. It should be:
dataFields[i].onblur = update;
And you were using the .value property when you called testPattern for the department field. But testPattern expects the argument to be the element, not the value. It should be:
if (testPattern(document.forms[0].department, /^DEPT\d{3}$/) == false)
window.onload = initPage;
/*initPage()
Initializes the contents of the Web page */
function initPage() {
//declare array variable dataFields points to input elements from the expenseEntry class
var dataFields = new Array();
var allElems = document.getElementsByTagName("*");
for (var i = 0; i < allElems.length; i++) {
if (allElems[i].className == "expenseEntry") dataFields.push(allElems[i]);
}
//add onblur event that runs update() function whenever focus leaves a datafield.
for (var i = 0; i < dataFields.length; i++) {
dataFields[i].onblur = update;
}
//event handler that runs validateForm() upon submitting the form.
document.forms[0].onsubmit = validateForm;
}
/* testLength()
Tests a field for its length. */
function testLength(field) {
if (field.value.length == 0) {
// Change the background color to white or yellow depending on the lenght.
field.style.backgroundColor = "yellow";
return false;
} else field.style.backgroundColor = "white";
return true;
}
/* testPattern()
Tests a field for its pattern. */
function testPattern(field, regx) {
if (regx.test(field.value)) {
field.style.backgroundColor = "white";
field.style.color = "black";
return true;
} else field.style.backgroundColor = "yellow";
field.style.color = "red";
return false;
}
/* validateForm()
Validates a Web form */
function validateForm() {
var isValid = true;
//testLength function with lname field also for fname, address, and summary to make sure an entry has been made.
if (testLength(document.forms[0].lname) == false) {
isValid = false;
}
if (testLength(document.forms[0].fname) == false) {
isValid = false;
}
if (testLength(document.forms[0].address) == false) {
isValid = false;
}
if (testLength(document.forms[0].summary) == false) {
isValid = false;
}
//must match ACT followed by six digits
if (testPattern(document.forms[0].account, /^ACT\d{6}$/) == false)
{
isValid = false;
}
//dept field. regx should match DEPT followed by three digits
if (testPattern(document.forms[0].department, /^DEPT\d{3}$/) == false)
{
isValid = false;
}
//Project field with regx should match PROJ followed by five digits
if (testPattern(document.forms[0].project, /^PROJ\d{5}$/) == false)
{
isValid = false;
}
//call testPattern function to test SSN. match 9 digits or text string
if (testPattern(document.forms[0].ssn, /^\d{3}-\d{2}-\d{4}$/) == false) {
isValid = false;
}
if (isValid == false)
{
alert("Please fill out all required fields in the proper format.");
}
return isValid;
}
/* calcRow
Calculates the costs within one row of the travel report */
function calcRow(row) {
var travel = parseFloat(document.forms[0].elements["travel" + row].value);
var lodge = parseFloat(document.forms[0].elements["lodge" + row].value);
var meal = parseFloat(document.forms[0].elements["meal" + row].value);
return travel + lodge + meal;
}
/* calcTotal()
Calculates the total cost of the travel */
function calcTotal() {
//create a variable totalEXP
var totalExp = 0;
//create a for loop that runs 1 t0 4
for (var i = 1; i <= 4; i++)
// increase the value of totalExp by value returned for calcRow
{
totalExp += calcRow(i);
}
return totalExp;
}
/* upDate()
Updates the total travel cost */
function update() {
//create a variable numRegExp
var numRegExp = /^\d*(\.\d{0,2})?$/;
// Test weather the currently selected object matches the numRegExp pattern
if (numRegExp.test(this.value)) {
// Display the value of the current object to 2 decimal places.
parseInt(this.value).toFixed(2);
//insert a for loop that runs 1 to 4 for all the expense rows in the form
for (var i = 1; i < 4; i++) {
//Set the value of sub[i] field to the value returned by calcRow()
document.forms[0].elements["sub" + i].value = calcRow(i).toFixed(2);
//set the value of the total field equal to the value returned by the calTotal() function
document.forms[0].total.value = calcTotal().toFixed(2);
}
}
//if the condition is not met display alert and change value.
else if (numRegExp.test(this.value) == false) {
alert("Invalid currency value");
(this.value = "0.00");
this.focus();
}
}
body {
background: white url(back.jpg) repeat-y scroll 0px 0px
}
#links {
position: absolute;
top: 10px;
left: 0px
}
#main {
border: 1px solid black;
width: 640px;
padding: 5px;
background-color: white;
margin-left: 100px;
margin-top: 0px
}
span {
color: red;
font-family: Arial, Helvetica, sans-serif;
font-size: 9pt
}
table {
font-size: 8pt;
width: 630px;
margin-top: 5px;
margin-bottom: 0px
}
th {
background-color: rgb(153, 204, 255);
text-align: left;
font-weight: normal;
font-family: Arial, Helvetica, sans-serif
}
#reporttitle {
background-color: white;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 18pt;
color: rgb(153, 204, 255);
font-weight: bold
}
input {
width: 100%;
font-size: 8pt
}
select {
width: 100%;
font-size: 8pt
}
#lname,
#fname {
width: 150px
}
#account,
#department,
#project {
width: 150px
}
#traveltable th {
text-align: center
}
#subhead {
width: 100px
}
#travelexphead,
#lodgeexphead,
#mealexphead {
width: 80px
}
#date1,
#date2,
#date3,
#date4 {
text-align: center
}
#travel1,
#travel2,
#travel3,
#travel4 {
text-align: right
}
#lodge1,
#lodge2,
#lodge3,
#lodge4 {
text-align: right
}
#meal1,
#meal2,
#meal3,
#meal4 {
text-align: right
}
#sub1,
#sub2,
#sub3,
#sub4,
#total {
text-align: right
}
#traveltable #totalhead {
text-align: right
}
textarea {
height: 100px;
width: 100%
}
#main #psub {
text-align: center
}
#main p input {
width: 190px;
background-color: rgb(153, 204, 255);
color: black;
letter-spacing: 5
}
<?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">
<head>
<!--
New Perspectives on JavaScript, 2nd Edition
Tutorial 5
Case Problem 2
Expense Report Form
Author: Gavin Macken
Date: 8 March `15
Filename: exp.htm
Supporting files: back.jpg, exp.css, links.jpg, logo.jpg, report.js
-->
<title>Expense Report</title>
<link href="exp.css" rel="stylesheet" type="text/css" />
<script src="report.js" type="text/javascript"></script>
</head>
<body>
<form id="expform" method="post" action="done.htm">
<div id="links">
<img src="links.jpg" alt="" />
</div>
<div id="main">
<p>
<img src="logo.jpg" alt="DeLong Enterprises" />
</p>
<table cellspacing="2">
<tr>
<th colspan="5" id="reporttitle">Travel Expense Report</th>
</tr>
<tr>
<th>Name (Last)<span>*</span>
</th>
<th>(First)<span>*</span>
</th>
<th>(Initial)</th>
<th>Account<span>*</span>
</th>
<td>
<input name="account" id="account" />
</td>
</tr>
<tr>
<td>
<input name="lname" id="lname" />
</td>
<td>
<input name="fname" id="fname" />
</td>
<td>
<input name="init" id="init" />
</td>
<th>Department<span>*</span>
</th>
<td>
<input name="department" id="department" />
</td>
</tr>
<tr>
<th>Social Security Number<span>*</span>
</th>
<td colspan="2">
<input name="ssn" id="ssn" />
</td>
<th>Project<span>*</span>
</th>
<td>
<input name="project" id="project" />
</td>
</tr>
</table>
<table cellspacing="2">
<tr>
<th>Send Check to:<span>*</span>
</th>
<th>Trip Summary<span>*</span>
</th>
</tr>
<tr>
<td>
<textarea id="address" name="address" rows="" cols=""></textarea>
</td>
<td>
<textarea id="summary" name="summary" rows="" cols=""></textarea>
</td>
</tr>
</table>
<table id="traveltable" cellspacing="2">
<tr>
<th id="datehead">Travel Date</th>
<th id="travelexphead">Travel Cost</th>
<th id="traveltypehead">Type</th>
<th id="lodgeexphead">Lodging</th>
<th id="mealexphead">Meals</th>
<th id="subhead">Total</th>
</tr>
<tr>
<td>
<input name="date1" id="date1" />
</td>
<td>
<input name="travel1" id="travel1" value="0.00" class="expenseEntry" />
</td>
<td>
<select name="traveltype1" id="traveltype1">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td>
<input name="lodge1" id="lodge1" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="meal1" id="meal1" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="sub1" id="sub1" value="0.00" readonly="readonly" />
</td>
</tr>
<tr>
<td>
<input name="date2" id="date2" />
</td>
<td>
<input name="travel2" id="travel2" value="0.00" class="expenseEntry" />
</td>
<td>
<select name="traveltype2" id="traveltype2">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td>
<input name="lodge2" id="lodge2" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="meal2" id="meal2" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="sub2" id="sub2" value="0.00" readonly="readonly" />
</td>
</tr>
<tr>
<td>
<input name="date3" id="date3" />
</td>
<td>
<input name="travel3" id="travel3" value="0.00" class="expenseEntry" />
</td>
<td>
<select name="traveltype3" id="traveltype3">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td>
<input name="lodge3" id="lodge3" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="meal3" id="meal3" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="sub3" id="sub3" value="0.00" readonly="readonly" />
</td>
</tr>
<tr>
<td>
<input name="date4" id="date4" />
</td>
<td>
<input name="travel4" id="travel4" value="0.00" class="expenseEntry" />
</td>
<td>
<select name="traveltype4" id="traveltype4">
<option>air</option>
<option>auto</option>
<option>taxi</option>
<option>train</option>
</select>
</td>
<td>
<input name="lodge4" id="lodge4" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="meal4" id="meal4" value="0.00" class="expenseEntry" />
</td>
<td>
<input name="sub4" id="sub4" value="0.00" readonly="readonly" />
</td>
</tr>
<tr>
<th colspan="5" id="totalhead">TOTAL</th>
<td>
<input id="total" name="total" readonly="readonly" value="0.00" />
</td>
</tr>
<tr>
<td colspan="6"><span>* - Indicates a required field</span>
</td>
</tr>
</table>
<p id="psub">
<input type="submit" value="Submit Report" />
</p>
</div>
</form>
</body>
</html>

Categories