Delete records from a table (Firebase) - javascript

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

Related

JS and jQuery Address Book - search function not working (amongst other problems)

I'm very new to the development world (2 months) and I'm trying to get into a selective coding bootcamp. They've asked me to build an addressbook in JS, using HTML, CSS and jQuery, as part of the admissions process. I think I'm pretty close but I can't get my solution to do exactly what it needs.
So this is what I've got so far in JS/jQuery:
// creating an address book constructor, which will contain all our contacts
function AddressBook() {
this.contacts = [];
}
// creating function that adds contacts to the array
AddressBook.prototype.addContact = function (contactToAdd) {
this.contacts[this.contacts.length] = contactToAdd;
};
// creating a contact search function
AddressBook.prototype.searchContact = function (searchTerm) {
for (let i = 0; i < this.contacts.length; i++) {
if (
searchTerm === this.contacts[i].firstName ||
this.contacts[i].lastName ||
this.contacts[i].phoneNumber ||
this.contacts[i].address
) {
return this.contacts[i];
}
return false;
}
};
//creating a delete function
AddressBook.prototype.deleteContact = function (contactToDelete) {
for (let i = 0; i < this.contacts.length; i++) {
if (contactToDelete === this.contacts[i]) {
delete this.contacts[i];
}
}
};
// creating contacts as objects with certain properties and values
function Contact(firstName, lastName, phoneNumber, address) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.address = address;
}
function displayContacts(addressBookDisplay) {
let htmlForTable = "";
for (let i = 0; i < addressBookDisplay.contacts.length; i++) {
const contact = addressBookDisplay.contacts[i];
htmlForTable +=
"<tr>" +
"<td>" +
contact.firstName +
"</td>" +
"<td>" +
contact.lastName +
"</td>" +
"<td>" +
contact.phoneNumber +
"</td>" +
"<td>" +
contact.address +
"</td>" +
"</tr>";
}
$("#contact-table-start").html(htmlForTable).appendTo("table");
}
function showContact(contact) {
if (contact !== undefined) {
$("#show-search-results").show();
const contactFirst = contact.firstName;
const contactLast = contact.lastName;
const contactPhone = contact.phoneNumber;
const contactAddress = contact.address;
$(".first-name").text(contactFirst);
$(".last-name").text(contactLast);
$(".phone-number").text(contactPhone);
$(".address").text(contactAddress);
let button = $("#delete-button");
button.empty();
button.attr("name", contactFirst);
button.append("<button class='deleteButton'>Delete</button>");
} else {
$("#yes-results").hide();
$("#no-results").text("No result matches your search, try again?");
}
}
let addressBook = new AddressBook();
$(document).ready(function () {
$("#add-form").on("submit", function (event) {
event.preventDefault();
// creating variables storing input from addform
const firstNameForm = $("[name=new-first-name]").val();
const lastNameForm = $("[name=new-last-name]").val();
const phoneNumberForm = $("[name=new-phone-number]").val();
const addressForm = $("[name=new-address]").val();
$("[name=new-first-name]").val("");
$("[name=new-last-name]").val("");
$("[name=new-phone-number]").val("");
$("[name=new-address]").val("");
let newContact = new Contact(
firstNameForm,
lastNameForm,
phoneNumberForm,
addressForm
);
addressBook.addContact(newContact);
displayContacts(addressBook);
});
});
$(document).ready(function () {
$("#search-form").on("submit", function (event) {
event.preventDefault();
// creating variables storing input from searchform
const searchForm = $("[name=searchterm]").val();
$("[name=searchterm]").val("");
const searchcontact = addressBook.searchContact(searchForm);
showContact(searchcontact);
});
});
$(document).ready(function () {
$("#delete-button").on("click", function (event) {
event.preventDefault();
let contactDelFirst = $("#delete-button").attr("name");
let contactToDelete = searchContact(contactDelFirst);
addressBook.deleteContact(contactToDelete);
showContact(contactToDelete);
});
});
This is my HTML if needed:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Elise's Address Book</title>
<link href="./Style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="./Script.js"></script>
</head>
<body>
<header>
<h1>Elise's Address Book</h1>
</header>
<main>
<section>
<div id="search-contact">
<h2>Search Contacts</h2>
<form action="#" id="search-form">
<div>
<input
type="text"
name="searchterm"
placeholder="Enter contact's full name"
/>
<input type="submit" />
</div>
</form>
</div>
<div id="show-search-results">
<div id="yes-results">
<h2>Your Contact</h2>
<p>First Name: <span class="first-name"></span></p>
<p>Last Name: <span class="last-name"></span></p>
<p>Phone Number: <span class="phone-number"></span></p>
<p>Address: <span class="address"></span></p>
<div id="delete-button"></div>
</div>
<div id="no-results">
<span></span>
</div>
</div>
<div id="contact-list">
<h2>All Contacts</h2>
<table id="contact-table-start">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
</table>
</div>
<div id="add-contact">
<h2>Add New Contact</h2>
<form action="#" id="add-form">
<div>
<input
type="text"
name="new-first-name"
placeholder="Enter first name"
required
/>
<input
type="text"
name="new-last-name"
placeholder="Enter last name"
required
/>
<input
type="text"
name="new-phone-number"
placeholder="Enter phone number (incl. country code)"
pattern="^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"
required
/>
<!--check pattern-->
<input
type="text"
name="new-address"
placeholder="Enter address"
required
/>
<input type="submit" />
</div>
</form>
</div>
</section>
</main>
<footer>
<p>Coded by <em>Elise Verhoeye</em></p>
</footer>
</body>
</html>
My main concerns are:
My search function isn't working as it should, it only ever outputs the first element in the array of contacts.
The new contacts I am adding are being added into the first column, so it's a table within a table, even though my new HTML has td (table data) elements in it.
Does anyone know how I can get this fixed?
Many thanks in advance!

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>

Pull value from HTML field and put into variable using get.element

How would i pull the user field info from the fields and store in a variable?
I need it to then output that information into a div, its for an employee records database kind of thing.
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
heres my empty js
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
please make it as simple as possible
cheers! any help will be appreciated!
Im fairly new to js and coding in general.
For getting values from HTML form fields from where you want to get value
var x = document.getElementById("myText").value;
and you can set it as where you want to set
document.getElementById("result").value = x;
I agree with #Rao and you can read this post that talk about how to get input field...
How do I get the value of text input field using JavaScript?
You can read from mozilla site
https://developer.mozilla.org/it/docs/Web/JavaScript/Guida
And w3schools...
https://www.w3schools.com/js/

Saving form data using localstorage and dynamically reading data to a table

I am currently creating a signup form for a client and one of the requirements is for the form to be able to transmit and store data offline. I have already tried to work with a database, but I am still in beginning stages learning php so I decided t quit while I am behind.
I found another method of storign data locally suing localstorage with JS, but I am unable to display the stored data in a dynamic table.
Any help on this matter would be greatky appreciated, here is the code I have so far
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem(), false);
window.onload = function() {
storageLogic.loaddata();
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>
There are primarily two errors you need to fix:
Move the getElementById() and addEventListener() for id btnsubmit to your onload handler. The way it is now, it tries to find the element before it is actually in the DOM.
You are accidentally invoking the handler that is the second parameter of addEventListener(). In other words, get rid of the () after the second parameter.
Here is a version of your code with those changes that seems to minimally work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
window.onload = function() {
storageLogic.loaddata();
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem, false);
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>

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

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

Categories