Reputation: 2250
I apologize in advance for this simple question but its late and I don't want to sleep until I have it working...and I know my mind is numb from working on other parts for last many hours.
Basically, I am just trying to get the submit button to call the add()
function by assigning it with addEventListener
. When I click the button it clears the form but doesn't do anything else. If I fill in the fields and then call add()
in Chrome's JS console it works perfectly...clearly the event listener is not being added to the button and I don't want to call the function inline. Thanks in advance.
html:
<ul> <li> <label for="firstname">First Name:</label> <input type="text" id="firstname"/> </li> <li> <label for="lastname">Last Name:</label> <input type="text" id="lastname"/> </li> <li> <label for="email">Email:</label> <input type="text" id="email"/> </li> <li> <label for="subject">Subject:</label> <input type="text" id="subject"/> </li> <li> <input type="submit" value="Save" id="btnSave"/> </li> </ul>
JS:
var rolodex = localStorage.getItem('rolodex'); //load stored data if there is any
window.onload = function() {
rolodex = JSON.parse(rolodex);
if(rolodex === null) { //if no data, initialize an empty array
rolodex = [];
} else {
console.log(rolodex);
}
};
var add = function(){
var SME = JSON.stringify({
firstname:document.getElementById('firstname').value,
lastname:document.getElementById('lastname').value,
email:document.getElementById('email').value,
subject:document.getElementById('subject').value
});
rolodex.push(SME);
localStorage.setItem('rolodex', JSON.stringify(rolodex));
alert("Saved");
};
var submit = function(){
var btnSave = document.getElementById('btnSave');
btnSave.addEventListener('click', add(), false);
};
Upvotes: 0
Views: 271
Reputation: 2250
Someone posted a partial answer and then deleted it so I will put what I did.
Fixed add()
being called instead of assigned as just add
in the addEventListener
removed the submit function and put its contents in the window.onLoad
function so that it would be assigned automatically.
Upvotes: 1