how can i make my javascript to read the form value? - javascript

i'm trying to do a form that will allow the user to see the details that he put into the fields after he clicked the button. for some reason the javascript doesn't read the values of the text the user put into the form. any help?
<form>
first name:
<input type="text" autofocus autocomplete="on" placeholder="first name" required id="first">
last name:
<input type="text" autocomplete="on" placeholder="last name" required id="last">
year of birth:
<input type="number" pattern="^[0-9]{4}" id="year">
gender:
<select id="sel">
<option selected>MALE</option>
<option>FEMALE</option>
</select>
<button id="butt">click</button>
</form>
the javascript :
function cont(){
function person()
{
this.FirstName = null;
this.LastName = null;
this.YearOfBirth = null;
this.Gender = null;
this.Weight = null;
this.Height = null;
this.Country = null;
this.FullName = function()
{
return this.FirstName + " " + this.LastName
};
this.Age = function()
{
var today = new Date();
var yy = today.getFullYear();
return yy - this.YearOfBirth;
};
this.toString = function()
{
return "this rider lives in " + this.Country + " and his name is " + this.FirstName + " " + this.LastName;
};
}
var rider = new person
rider.FirstName = document.getElementById('first').value
rider.LastName = document.getElementById('last').value
rider.YearOfBirth = document.getElementById('year').value
rider.Gender = document.getElementById('sel').value
document.getElementById('butt').onclick = function()
{
if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
{
alert ("fill all the required fields")
}
else
{
document.write(rider.FirstName + "<br>")
document.write(rider.LastName + "<br>")
document.write(rider.YearOfBirth + "<br>")
document.write(rider.Gender + "<br>")
document.write(rider.FullName() + "<br>")
}
} }

You are setting the "rider." values when the page loads (and they are empty) but not getting them again when the user clicks the button. Thus, the document.write functions are just writing empty values. Try:
document.getElementById('butt').onclick = function()
{
rider.FirstName = document.getElementById('first').value;
rider.LastName = document.getElementById('last').value;
rider.YearOfBirth = document.getElementById('year').value;
rider.Gender = document.getElementById('sel').value;
if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
{
alert ("fill all the required fields");
}
else
{
document.write(rider.FirstName + "<br>");
document.write(rider.LastName + "<br>");
document.write(rider.YearOfBirth + "<br>");
document.write(rider.Gender + "<br>");
document.write(rider.FullName() + "<br>");
}
} }

Related

javascript alert showing code insted of string

first and foremost i'm new to javascript and coding. second, i'm coding a book store project with javascript with an alert message that shows each customer's total factor. but the alert message shows the code of my function "printFactor" insted of the string that is made by this function. this is my code:
function Book(name, writer, date, price)
{
this.name = name;
this.writer = writer;
this.date = date;
this.price = price;
}
function Customer(name, gender, turn)
{
this.name = name;
this.gender = gender;
this.turn = turn;
this.numberOfBooks = 0;
this.totalSum = 0;
this.bookList = [new Book("-", "-", "-", 0)];
//Functions.
this.addBook = function (newBook) {
this.numberOfBooks++;
this.bookList.push(newBook);
};
this.printFactor = function () {
var message = "";
if (this.numberOfBooks === 0) {
message = "No Books Has Been Added to Book List!";
return (message);
}
else {
message = this.name + " " + this.gender + " Number of Books: " + this.numberOfBooks + " Customer's Turn: " + this.turn + "\nBooks:\n";
var i;
var newMessage;
for (i = bookList.length - 1; i > 0; i--) {
newMessage = bookList[i].name + " " + bookList[i].writer + " " + bookList[i].date + " " + bookList[i].price.toString() +"\n" ;
message += newMessage;
this.totalSum += bookList[i].price;
this.bookList.pop();
}
newMessage = "Total Sum: " + this.totalSum;
message += newMessage;
return (message);
}
};
}
var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29", 13000);
var faramarz = new Customer("faramarz", "Male", 3);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
var m = faramarz.printFactor;
window.alert(m);
You need to invoke the function:
var m = faramarz.printFactor();
As is your variable m contains a reference to the function, but you need to call it to get the result.
var m = faramarz.printFactor();
window.alert(m);
You simply don't call your function, this should work.
var m = faramarz.printFactor()
Beside you reference an unexisting variable 'booklist', that should be "this.booklist"
for (i = this.bookList.length - 1; i > 0; i--) {
newMessage = this.bookList[i].name + " " + this.bookList[i].writer + " " + this.bookList[i].date + " " + this.bookList[i].price.toString() +"\n" ;
You need to actually call the function by adding () to the end, like this:
var m = faramarz.printFactor()

Input to object

My question is: How to migrate var x which is basically user input data to var person so user could change person.firstName by inputing data into <input type="text" id="userInput" value=""> element. I am very new for JS concepts, so I would be appreciate for any help. Thank you.
var person = {
firstName : "John",
lastName : "Doe",
age : 30,
fullName : function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName (); // Result: My name is John Doe I am 30 yers old
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = x;}
You can add the event input to your input field.
Set the entered input (firstName) to your object person.
Look this code snippet:
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName();
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
person.firstName = x;
document.getElementById("demo").innerHTML = person.fullName();
}
document.getElementById("userInput").addEventListener('input', myFunction);
<span id='demo'></span>
<p>User Input</p>
<input type="text" id="userInput" value="">
See? The object person is being updated automatically.
Resource
EventTarget.addEventListener()
Working with objects
Just do what you say:
function updateFirstName() {
person.firstName = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = person.fullName();
}

Trying to grab a innerhtml from within a innerhtml

So i've recently ran into issues with trying to move specific pieces of a <p> </p> called result. as such i thought hey! wouldn't be easier to break each part inside of result down into another <p>!? well it works lol however trying to grab that inner <p> that in this cause we'll call vault is being difficult. I've tried several methods but cant seem to grab it's value from outside in a document.getElementByID....here's the code below for the html.
document.getElementById("result").innerHTML = Monster + "<p id='vault'> || HP: " + HP + "</p> || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
then the script that eventually calls it
function Combat(id){
document.getElementById("vault").innerHTML = id;
document.getElementById("C").value = id
}
So what i'm trying is change id "C" to ID"VAULT" inside of id ("result").
any ideas on why i can't grab vault?
What you want would be easier with Object-oriented JavaScript.
Usually when coding JavaScript you want to be as independent of the DOM (HTML) as possible.
Consider the following example:
/**
* Monster
*/
var Monster = (function() {
function Monster(HP, DEF, ATK, DB, RET, INT, MEXP) {
if (HP === void 0) {
HP = 100;
}
if (DEF === void 0) {
DEF = 10;
}
if (ATK === void 0) {
ATK = 100;
}
if (DB === void 0) {
DB = 10;
}
if (RET === void 0) {
RET = true;
}
if (INT === void 0) {
INT = 100;
}
if (MEXP === void 0) {
MEXP = 100;
}
this.HP = HP;
this.DEF = DEF;
this.ATK = ATK;
this.DB = DB;
this.RET = RET;
this.INT = INT;
this.MEXP = MEXP;
}
/**
* getHTML
*/
Monster.prototype.getHTML = function() {
return "HP: " + this.HP + " || Defense: " + this.DEF + " || Attack: " + this.ATK + " || Can it Dodge/Block: " + this.DB + " || Can it retaliate: " + this.RET + " || Initative: " + this.INT + " || Exp: " + this.MEXP;
};
/**
* attacked
*/
Monster.prototype.attacked = function(damage) {
if (damage === void 0) {
damage = 0;
}
//check defences
if (damage > this.DEF + this.DB) {
//take damage
this.HP -= (damage - this.DEF + this.DB);
}
if (this.HP < 0) {
//Return true if it slew the monster
return true;
} else {
//Return false if the monster survived
return false;
}
};
return Monster;
}());
/**
* Area
*/
var Area = (function() {
function Area(name) {
if (name === void 0) {
name = "Vault";
}
this.name = name;
this.monsters = [];
}
/**
* addMonster
*/
Area.prototype.addMonster = function(monster) {
this.monsters.push(monster);
return this;
};
/**
* attackVault
*/
Area.prototype.assault = function(damage) {
if (damage === void 0) {
damage = 0;
}
//If no monster
if (this.monsters.length < 1) {
alert("You have cleared this vault");
return true;
} else {
//If monsters exists, attack the first
var monsterKilled = this.monsters[0].attacked(damage);
//If the monster was killed
if (monsterKilled) {
//remove monster
this.monsters.splice(0, 1);
//Alert the player
alert("Well done hero!\nOnly " + (this.monsters.length) + " remaining!");
}
}
//Return maybe monsters left?
return this.monsters.length < 1;
};
return Area;
}());
////GRAP HTML ELEMENT
var output = document.getElementById("current-monster");
////RUNNING YOUR GAME
//Build and populate world
var vault = new Area();
vault
.addMonster(new Monster())
.addMonster(new Monster());
//INTERACTION
alert("Start");
//Hit the vault till it is empty
while (vault.assault(45) != true) {
output.innerHTML = vault.monsters[0].getHTML();
alert("Attack!");
}
output.innerHTML = "Victory!";
<h1 id="title">Monster Game!</h1>
<h2 id="current-monster"></h2>
See how i can easily access the data though JavaScript?
When coding a JavaScript game, it makes sense to keep important data and structures in your JavaScript.
Ok so i added the bit - ADyson suggested...
document.getElementById("result").innerHTML = Monster + "<p id='vault(" + loop + ")'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
}
}
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
var id = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = id;
submit();
}
However now when i run it on the " ).innerHTML;" i'm getting a
MonsterGen.html:426 Uncaught TypeError: Cannot read property
'innerHTML' of nullCombat # MonsterGen.html:426onclick #
MonsterGen.html:1
Ok I found out exactly was was going wrong; it was the naming convention in the <P>.
Originally it was id='vault(" + loop + ")'... this would make it vault(1) etc.... however the getElement was getting it by this call ("vault" + id) so it would call vault1....thus two separate id's entirely....that's why it was returning null.
So I removed the () in the equation and now everything is working beautifully.

Why does "\n" create a new line even when told not to?

I am having a problem with "\n" creating a line even when it is told not to when copying. The fix is probably something simple that I am just not seeing for some reason. I would appreciate any input or coaching on this problem.
(Please only give me Javascript answers as I am not interested in jquery or other methods)
<script type="text/javascript">
if (pullDownResponseE == "")
{
}
else {
var pullDownValuesE = document.getElementById("taskOne");
var pullDownResponseE = pullDownValuesE.options[pullDownValuesE.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponseE;
}
if (pullDownResponseF == "")
{
}
else{
var pullDownValuesF = document.getElementById("taskTwo");
var pullDownResponseF = pullDownValuesF.options[pullDownValuesF.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponseF;
}
</script>
As you can see, pullDownResponseF and pullDownReponseE should do nothing if my dropdown value equals "" and this portion works for the most part, it doesn't execute any of the else code EXCEPT for the new line "\n" part.
Can anyone explain what is going wrong here?
EDIT: Having more code might help here. I'll only include the essential portions since it is so long.
<script type="text/javascript">
function copyNotesTemplate()
{
var stuffToCopy = document.getElementById('myForm').value;
if(stuffToCopy.length > 1)
{
var stuffToCopy = "PT meets criteria" + "\n" + document.getElementById('myForm').value;
}
if(document.getElementById('noPtCriteria').checked)
{
var stuffToCopy = document.getElementById('noPtCriteria').value;
}
if (pullDownResponsee == "")
{
}
else {
var pullDownValuese = document.getElementById("taskOne");
var pullDownResponsee = pullDownValuese.options[pullDownValuese.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponsee;
}
if (pullDownResponsef == "")
{
}
else{
var pullDownValuesf = document.getElementById("taskTwo");
var pullDownResponsef = pullDownValuesf.options[pullDownValuesf.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponsef;
}
if (pullDownResponseg == "")
{
}
else{
var pullDownValuesg = document.getElementById("taskThree");
var pullDownResponseg = pullDownValuesg.options[pullDownValuesg.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponseg;
}
var tempValues = document.getElementById('whatUpdate').value
if(tempValues.length > 1)
{
var stuffToCopy = stuffToCopy + "Updated" + " " + document.getElementById('whatUpdate').value + " ";
}
else{
}
var tempValuess = document.getElementById('whatInfo').value
if(tempValuess.length > 1)
{
var stuffToCopy = stuffToCopy + "per" + " " + document.getElementById('whatInfo').value + "\n";
}
else{
}
var tempValue = document.getElementById('whatDSCRP').value
if(tempValue.length > 1)
{
var stuffToCopy = stuffToCopy + document.getElementById('whatDSCRP').value + " " + "dscrp on Collection tube and trf was resolved using" + " ";
}
else{
}
var tempValue = document.getElementById('resolveIT').value
if(tempValue.length > 1)
{
var stuffToCopy = stuffToCopy + document.getElementById('resolveIT').value + " ";
}
else{
}
var tempValue = document.getElementById('tubeCorrect').value
if(tempValue.length > 1)
{
var stuffToCopy = stuffToCopy + "trf was" + " " + document.getElementById('tubeCorrect').value;
}
else{
}
if(stuffToCopy.length > 1)
{
var stuffToCopy = stuffToCopy + "\n" + document.getElementById('moreNotes').value;
}
else{
}
if (pullDownResponsesu == "")
{
}
else{
var pullDownValuesu = document.getElementById("mod33Apply");
var pullDownResponsesu = pullDownValuesu.options[pullDownValuesu.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponsesu;
}
if (pullDownResponsesb == "")
{
}
else{
var pullDownValuesb = document.getElementById("resultICR");
var pullDownResponsesb = pullDownValuesb.options[pullDownValuesb.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponsesb + "," + " ";
}
if (pullDownResponsesc == "")
{
}
else{
var pullDownValuesc = document.getElementById("moneyNCIS");
var pullDownResponsesc = pullDownValuesc.options[pullDownValuesc.selectedIndex].value;
stuffToCopy = stuffToCopy + pullDownResponsesc + " ";
}
if (pullDownResponsesd == "")
{
}
else{
var pullDownValuesd = document.getElementById("resultMMT");
var pullDownResponsesd = pullDownValuesd.options[pullDownValuesd.selectedIndex].value;
stuffToCopy = stuffToCopy + pullDownResponsesd;
}
if(stuffToCopy.length > 1)
{
var stuffToCopy = stuffToCopy + " " + "Reason:" + " " + document.getElementById('whyNotEligible').value;
}
else{
}
if (pullDownResponsesa == "")
{
}
else{
var pullDownValuesa = document.getElementById("testReleased");
var pullDownResponsesa = pullDownValuesa.options[pullDownValuesa.selectedIndex].value;
stuffToCopy = stuffToCopy + "\n" + pullDownResponsesa;
}
window.clipboardData.setData('text', stuffToCopy);
}
</script>
If somebody skips filling out a note field or skips a dropdown in this example then it will not execute the code like I intended but it does create a new line when copied like this:
taskOne selected
(extra line here since task two wasn't selected)
taskThree selected
I would like there not to be an extra line between Task one and three if task two is skipped. Like this:
taskOne selected
taskThree selected
Note: I know that having else {} is pointless but it helps me visually.
I created snips of exactly what it looks like when copy/pasted from my tool that you can view here if you would like:
Example 1: http://imgur.com/wGO5vnT
Example 2: http://imgur.com/UX1tG5S
Here is an example of my html as well:
<html lang="en">
What tasks are needed for the case?
<br />
<select class="style3" id="taskOne">
<option value=""></option>
<option value="ABN needed">ABN needed</option>
<option value="Auth needed">Auth needed</option>
</select>
</html>
No, it doesn't add a new line, see:
stuffToCopy = "";
controlGroup = "a\nb";
pullDownResponseE = "";
if (pullDownResponseE == "")
{
}
else {
var pullDownValuesE = "taskOne";
var pullDownResponseE = "value";
stuffToCopy = stuffToCopy + "\n" + pullDownResponseE;
}
alert("stuffToCopy:"+stuffToCopy+";(no new-line here)\ncontrolGroup:"+controlGroup);
My guess is that your html is printed in such away that the values you get from the inputs contain an extra new-line at the end. Try changing your html to be 1 line, without new-lines, and test again.
Instead of:
<option value="a
">b
</option>
try:
<option value="a">b</option>
Alright so I fixed it, should have used the almighty document.getElementById instead of attempting to use pullDownReponse for my if statements..
I simply changed the if statements like this:
if (pullDownResponseg == "")
{
}
To this:
if (document.getElementById("taskThree").value == "")
{
}
Thanks for the help from the sincere. (and ridiculous non-answers from the others)

Generating Divs with unique buttons for toggling hide/show

Im making a contacts book, and with each new entry it generates a Div with all the information inside. I have gotten as far as giving each generated div a unique ID, and each button generated with the Div a unique ID, however I am having trouble associating the buttons with the div and allowing it to perform functions (such as toggling the visibility of the div).
Any help you can give is greatly appreciated, as I will soon be bald from frustration.
Updated Code with suggestions
The code that generates the DIV and Button:
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
The entire code
var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ; //Declaring variables for the fields
var Contact = function(surname,firstName,date, phone , address , post, email, group){
this.surname = surname ;
this.firstName = firstName ;
this.birthdayDate = new Date (date) ;
this.phone = phone;
this.address= address;
this.email = email;
this.post = post;
this.group = group;
this.selected = false ;
}
var contacts = [];
divid = 0;
buttonid = 1000;
myControls = [];
var getDate = function() {
for (var i= 0, j=contacts.length;i<j;i++){
var y = contacts[i].birthdayDate.getFullYear();
var m = contacts[i].birthdayDate.getMonth();
var d = contacts[i].birthdayDate.getDate();
contacts[i].days = d;
contacts[i].months = m + 1;
contacts[i].years = y ;
var today = new Date() ;
var ty = today.getFullYear();
contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);
}
}
var daysUntilBirthday = function(){
for (var i= 0, j=contacts.length;i<j;i++){
var today = new Date() ;
contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
if (contacts[i].daysUntil <= 0){
contacts[i].daysUntil = contacts[i].daysUntil + 365 ;
}
}
}
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts.push(a);
}else{ alert("Please complete all fields")}
}
var clearUI = function(){
var white = "#fff";
surnameField.value = "";
surnameField.style.backgroundColor = white;
firstNameField.value = "";
firstNameField.style.backgroundColor = white;
birthdayField.value="";
birthdayField.style.backgroundColor = white;
phoneField.value = "";
phoneField.style.backgroundcolor = white;
addressField.value = "";
addressField.style.backgroundcolor = white;
postField.value = "";
postField.style.backgroundcolor = white;
emailField.value = "";
emailField.style.backgroundcolor = white;
groupField.value="";
groupField.style.backgroundcolor = white;
}
var updateList = function(){
divid = 0;
buttonid = 1000;
myControls = []
var tableDiv = document.getElementById("parentDiv"),
cDiv = "<BR>" + "<div align='center'> Click a contact to expand</div>" ;
for (var i= 0, j=contacts.length;i<j;i++){
var cntct = contacts[i];
cDiv += cntct.generateDiv();
}
tableDiv.innerHTML = cDiv;
getDate();
daysUntilBirthday();
saveContacts();
}
var add = function(){
;
addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField);
clearUI();
daysUntilBirthday();
getDate();
updateList();
};
var saveContacts = function(){
var cntcts = JSON.stringify(contacts);
if (cntcts !==""){
localStorage.contacts = cntcts;
}else{
alert("Could not save contacts");
}
}
var loadContacts = function(){
var cntcts = "";
if(localStorage.contacts !== undefined){
cntcts = localStorage.contacts;
contacts = JSON.parse(cntcts);
var proto = new Contact();
for (var i=0; i<contacts.length; i++){
var cntct = contacts[i]
cntct.__proto__ = proto;
cntct.birthdayDate = new Date(cntct.birthdayDate);
}
}
}
var clearContacts = function(){
contacts = [];
updateList();
}
//var periodUpdate = function(){
// setInterval(updateList, 10000);
//}
window.onload = function(){
loadContacts();
updateList();
surnameField = document.getElementById("surname");
firstNameField = document.getElementById("firstName")
birthdayField = document.getElementById("birthday");
phoneField = document.getElementById("phone");
addressField = document.getElementById("address");
postField = document.getElementById("post");
emailField = document.getElementById("email");
groupField = document.getElementById("group");
addButton = document.getElementById("addButton");
addButton.onclick = add;
delButton = document.getElementById("delButton");
delButton.onclick = clearContacts;
clearUI();
// periodUpdate();
}
The HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="contacts.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.8.3.min.js">
$(document).ready(function(){
(".btnForDiv").on("click", function(){
// get the ID of the button
var id = $(this).prop("id");
var divid;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divid = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divid).toggle();
});
});
</script>
<div><title>Contacts Book</title></div>
</head>
<body>
<div class="information">
<heading><h1>Contacts Book</h1></heading>
</div>
<p><div class="information">Enter the contacts details below and click Add or select to view an existing contact.</div></p>
<hr>
<div class="entrydiv">
<table class="entryforms">
<br>
<tr>
<td>Surname</td><td><input type="text" class="inputboxes" id="surname" /></td>
</tr>
<tr>
<td>First Name</td><td><input type="text" class="inputboxes" id="firstName" /></td>
</tr>
<tr>
<td>Birthday</td><td><input type="date" class="inputboxes" id="birthday" /></td>
</tr>
<tr>
<td>Phone Number</td><td><input type="text" class="inputboxes" id="phone"></textarea></td>
</tr>
<tr>
<td>Email Address</td><td><input type="text" class="inputboxes" id="email" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" class="inputboxes" id="address"/></td>
</tr>
<tr>
<td>Postcode</td><td><input type="text" class="inputboxes" id="post" /></td>
</tr>
<tr>
<td>Group</td><td><select class="inputboxes" id="group"/>
<option value="Business">Business</option>
<option value="Educational">Educational</option>
<option value="Friend">Friend</option>
</td>
</tr>
</table>
<br>
<button id="addButton">Add Contact</button>
<button id="delButton">Delete Contacts</button>
</div>
<hr>
<div class="tablediv">
<h2 class="information" align="center">Contacts</h2>
<div id="parentDiv"></div>
</div>
</body>
</html>
The Solution
First of all massive thanks to Darren for his advice, which turns out to be spot on (with minor change)
First error I made was inserting jquery, I had
<script src="jquery-1.8.3.min.js">
//code
</script>
When I needed
<script src="jquery-1.8.3.min.js"></script>
<script>
//code
</script>
So that very minor mistake held me back for a while.
Secondly I used:
$(document).on('click','.btnForDiv',function(){
To call the Onclick event for my btnForDiv class buttons and the rest was all Darren :)
Thanks again
You could do a few things here.
One idea would be to store your generated div and button ID's in an array. You can then search this array for a given button ID to find its corresponding div.
For example (not tested...)
// outside your generatedDiv method
var myControls = new Array();
// then inside your generatedDiv method
var control = new Array();
control[0] = divId;
control[1] = buttonId;
myControls.push(control);
When you click your button you can grab its ID then search through the myControls array and look for the corresponding div
you could do a single function in jQuery to handle all the click for all of your generated buttons.
again (not tested) - give all your buttons a class, for example btnForDiv
$(document).ready(function(){
$(".btnForDiv").click(function(){
// get the ID of the button
var id = $(this).prop("id");
var divId;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divId = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divId).toggle();
});
});
I'm not 100% sure what your question was, though took a stab in the dark to help..
UPDATE
Because your div's are generated and added to the DOM dynamically you may have to use on instead of click - this will bind the click event to dynamic elements.
So try this:
$(".btnForDiv").on("click", function(){
// get the id.... etc...
});
also, make sure you did add the class btnForDiv to your dynamically generated buttons
this.firstName + " " + this.surname + "<button style='color: black;' id='" + buttonid + "b'" + " class='btnForDiv'> Button </button>" +

Categories

Resources