Ok, here is the thing.
I have posted 2 days in a row and you guys have helped me a lot! And know I am almost done with the project, only a few things left, and a will ask another question later here.
But to the point!
I am trying to use the .style.display = ... in my javascript and it doesnt work.
I dont know if the function isnt calling or if I have done it all wrong?
What I am trying to accomplish is that when I press the button "newButton" I got a form field, and after I am finished with the form I press the button "addContact" that is created with the form all dynamically with javascript I want the form to hide. How can I do that?
The form is not gonna submit to a php and that is why a have button and not submit, because the form is gonna display at the HTML (DOM) and show like a contactlist.
Hope you could help me out!
Here is the code.
//Contactlist funktion
function Contact(fname, lname, address, email, phone) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
this.phone = phone;
}
//The contacts
var contacts = [];
var ul1 = document.createElement('ul');
ul1.id = ('nav');
// Appending the objects
function theContacts() {
var body = document.getElementsByTagName('body')[0],
length = contacts.length;
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.innerHTML = cont.fname + ' ' + cont.lname;
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); ul1.appendChild(li);
}
body.appendChild(ul1);
}
// Calling the object
function addForms(){
var body = document.getElementsByTagName('body')[0]
var form = document.createElement("form");
form.id = 'formList';
var myArray = ['fnameValue', 'lnameValue', 'addressValue', 'emailValue', 'phoneValue'];
var texts = ['First Name: ', 'Last Name: ', 'Address: ', 'Email: ', 'Phone: '];
// Create a loop of 5
for(var i = 0; i < 5; i++){
var input = document.createElement('input');
var newlabel = document.createElement('label');
newlabel.innerHTML = texts[i];
form.appendChild(newlabel);
input.setAttribute('type','text');
input.setAttribute('id', myArray[i]);
// adds the input's to the form.
form.appendChild(input);
}
// adds the forms to the body
body.appendChild(form);
// Add Contact Button
var addContact = document.createElement('input')
addContact.setAttribute('type', 'button')
addContact.setAttribute('id', 'addContact')
addContact.addEventListener('click', onClick);
addContact.setAttribute('value', 'Add Contact')
form.appendChild(addContact);
/* var knapp = document.getElementById('addContact');
knapp.addEventListener('click', addNewContact) */
}
function addNewContact() {
var input1 = document.getElementById('fnameValue').value;
var input2 = document.getElementById('lnameValue').value;
var input3 = document.getElementById('addressValue').value;
var input4 = document.getElementById('emailValue').value;
var input5 = document.getElementById('phoneValue').value;
contacts.length = 0;
contacts.push(new Contact(input1, input2, input3, input4, input5));
}
// Knappning för ny kontakt
var button = document.getElementById("newButton");
button.addEventListener("click", addForms);
Here is the last part of the code that I am trying to apply but doesnt work for me...
function onClick() {
var div = document.getElementById('formlist');
if (addForms.style.display !== 'none') {
addForms.style.display = 'none';
}
else {
addForms.style.display = 'block';
}
};
Here you have an JS FIDDLE for example: http://jsfiddle.net/192ds38a/
That one shows how it works now withuot the "onClick" function.
But what I want is to hide the form when the AddContact button is pressed. That button is now made to add the information to the objects, but I also want that to hide the form.
Simply add a document.getElementById("formList").remove()to the addNewContact function as you can see in http://jsfiddle.net/192ds38a/1/ . Or does this not meet your needs?
Related
I am trying to make a Library project using vanilla JS and I can't understand the behaviour of removeChild() and addEventListener() in the code.
var myLibrary = [];
var content = document.querySelector(".content");
var nameField = document.createElement("input");
var authorField = document.createElement("input");
var pagesField = document.createElement("input");
var readingStatusField = document.createElement("input");
var submitButton = document.createElement("button");
var form = document.createElement("form");
function Book(name, author, pages, status){
this.name = name;
this.author = author;
this.pages = pages;
this.status = status
}
Book.prototype.info = function(){
if(this.status === false){
return console.log(this.name + " " + "by " + this.author + "," + this.pages + " pages, " + "not read yet" )
}
else{
return console.log(this.name + " " + "by " + this.author + "," + this.pages + " pages, "+ "read" )
}
}
function addBookToLibrary(Book) {
myLibrary.push(Book);
}
function displayBooks(){
for(let x = 0; x < myLibrary.length; x++){
myLibrary[x].info();
}
}
function createBookForm() {
var form = document.createElement("form");
form.classList.add("book-form")
nameField.classList.add("formfield")
nameField.setAttribute("type", "text");
nameField.setAttribute("placeholder", "Name");
authorField.classList.add("formfield")
authorField.setAttribute("type", "text");
authorField.setAttribute("placeholder", "Author");
pagesField.classList.add("formfield")
pagesField.setAttribute("type", "text");
pagesField.setAttribute("placeholder", "Pages");
readingStatusField.classList.add("formfield")
readingStatusField.setAttribute("type", "text");
readingStatusField.setAttribute("placeholder", "Reading Status");
submitButton.innerHTML = "Add"
submitButton.classList.add("submitButton")
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("value", "Submit");
// submitButton.onclick("")
form.appendChild(submitButton);
form.appendChild(readingStatusField);
form.appendChild(pagesField);
form.appendChild(authorField);
form.appendChild(nameField);
content.appendChild(form);
}
function getInfoFromForm() {
submitButton.addEventListener('click', (e) => {
let bookName = nameField.value;
let authorName = authorField.value;
let noOfPages = pagesField.value;
let readingStatus = readingStatusField.value;
let newBook = new Book(bookName, authorName, noOfPages, readingStatus);
addBookToLibrary(newBook);
displayBooks();
nameField.value = "";
authorField.value = "";
pagesField.value = "";
readingStatusField.value = "";
content.innerHTML = ""
content.removeChild(form);
})
}
let addBookButton = document.querySelector(".addBook");
addBookButton.addEventListener("click", (e) => {
let content = document.querySelector(".content")
createBookForm();
getInfoFromForm();
deleteForm();
})
In createBookForm() function, I create a form and append it to the content div. It worked fine.
In getInfoFromForm() function, I try to get info from the form, and when submit button is clicked I want to create an Book object and store it in the myLibrary[] array.
Here things get out of hand for me.
First of all, the removeChild method doesnt work and doesn't remove the form element from the content.
Second when I try to console.log the books from myLibrary[], at first submit it shows correctly. When I try this second time, it shows the first book, second book THREE TIMES and an empty book.
WHY ISN'T removeChild removing the form element and why is cicking the submit button behaves the way it is behaving.
I have some code that builds elements of a list on a sidebar. If a button is clicked I want to clear the list and repopulate it with new results. Right now the information just adds to the list. I would like to clear all of the items in the list so I can readd them.
function buildLocationList(data) {
for (i = 0; i < data.locations.length; i++) {
var currentFeature = data.locations[i];
var prop = currentFeature.locations;
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = '<b>' + currentFeature.company; + '</b>'
var address = listing.appendChild(document.createElement('div'));
address.innerHTML = currentFeature.address;
var csz = listing.appendChild(document.createElement('div'));
csz.innerHTML = currentFeature.csz;
/*var hours = listing.appendChild(document.createElement('div'));
hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
hours.style.color = 'gray'; */
link.addEventListener('click', function(e){
// Update the currentFeature to the store associated with the clicked link
var clickedListing = data.locations[this.dataPosition];
// 1. Fly to the point
flyToStore(clickedListing);
// 2. Close all other popups and display popup for clicked store
createPopUp(clickedListing);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
}
}
For your particular case, add this before you do anything else:
document.getElementById('listings').innerHTML = "";
I have successfully created a Google form that populates from a spreadsheet using code adapted from here: https://www.youtube.com/watch?v=BYA4URuWw0s . Now I would like to make the form go to a specific question based on the answer of a previous question without losing the function of updating from the spreadsheet. I have tried to alter code from here: How to assign Go_To_Page in Form Service on Multiple Choice? , but have yet to have any luck. Below is what I have as of now. I am very new to coding and any help will be greatly appreciated. Thanks in advance!!!
//insert your form ID
var FORM_ID = '1iA8jX720Eqi_GKwiA1RJiWwzt3vJ8XOOAqh-SjO9mXM';
//insert your sheet name with a list
var EMP_SHEET_NAME = 'empROSTER';
//insert your range of lis
//insert list id (before run getItemsOfForm function and look at t as A1Notation
var range1 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM_ID = '1097376824';
/*
add date question? -
form.addDateItem()
.setTitle('Date of Work Performed')
*/
//insert your sheet name with a list
var JOB_SHEET_NAME = 'jobROSTER';
//insert your range of list as A1Notation
var range2 = 'C2:C';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM2_ID = '773657499';
//insert your sheet name with a list
var AT_SHEET_NAME = '300';
//insert your range of list as A1Notation
var range3 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM3_ID = '1884670833';
//insert your sheet name with a list
var DT_SHEET_NAME = '1000';
//insert your range of list as A1Notation
var range4 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM4_ID = '379969286';
//insert your sheet name with a list
var CT_SHEET_NAME = '2000';
//insert your range of list as A1Notation
var range5 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM5_ID = '128282987';
//insert your sheet name with a list
var HOURS_SHEET_NAME = 'hourROSTER';
//insert your range of list as A1Notation
var range6 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM6_ID = '1385334889';
//Section in question
function createGoTo(){
var af = FormApp.openById(FORM_ID);
var pAdmin = af.getItemById(AT_SHEET_NAME); //use findPageIds to get the page id of a pre-created page
var pDesign = af.getItemById(DT_SHEET_NAME);
var pCon = af.getItemById(CT_SHEET_NAME);
var item = ITEM2_ID
//create choices as an array
var choices = [];
choices.push(item.createChoice('Administration Job', pAdmin));
choices.push(item.createChoice('Design Job', pDesign));
choices.push(item.createChoice('Construction Job', pCon));
// assignes the choices for the question
item.setChoices(choices);
}
function findPageIds(){
var af = FormApp.getActiveForm();
var pages = af.getItems(FormApp.ItemType.PAGE_BREAK);
for (i in pages){
var pName = pages[i].getTitle();
var pId = pages[i].getId();
Logger.log(pName+":"+pId);
}
}
//End of section in question
function updateEmpName() {
var values_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(EMP_SHEET_NAME).getRange(range1).getValues();
values_[0][0] = values_[0][0].toString();
for(var i = 1; i < values_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values_[i][0] != "") {
values_[0].push(values_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM_ID);
list.asListItem().setChoiceValues(values_[0]);
}
function updateJobName() {
var values2_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(JOB_SHEET_NAME).getRange(range2).getValues();
values2_[0][0] = values2_[0][0].toString();
for(var i = 1; i < values2_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values2_[i][0] != "") {
values2_[0].push(values2_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM2_ID);
list.asListItem().setChoiceValues(values2_[0]);
}
function updateAdminTasks() {
var values3_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(AT_SHEET_NAME).getRange(range3).getValues();
values3_[0][0] = values3_[0][0].toString();
for(var i = 1; i < values3_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values3_[i][0] != "") {
values3_[0].push(values3_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM3_ID);
list.asListItem().setChoiceValues(values3_[0]);
}
function updateDesignTasks() {
var values4_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(DT_SHEET_NAME).getRange(range4).getValues();
values4_[0][0] = values4_[0][0].toString();
for(var i = 1; i < values4_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values4_[i][0] != "") {
values4_[0].push(values4_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM4_ID);
list.asListItem().setChoiceValues(values4_[0]);
}
function updateConstructionTasks() {
var values5_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(CT_SHEET_NAME).getRange(range5).getValues();
values5_[0][0] = values5_[0][0].toString();
for(var i = 1; i < values5_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values5_[i][0] != "") {
values5_[0].push(values5_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM5_ID);
list.asListItem().setChoiceValues(values5_[0]);
}
function updateHours() {
var values6_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(HOURS_SHEET_NAME).getRange(range6).getValues();
values6_[0][0] = values6_[0][0].toString();
for(var i = 1; i < values6_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values6_[i][0] != "") {
values6_[0].push(values6_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM6_ID);
list.asListItem().setChoiceValues(values6_[0]);
}
function getItemsOfForm(){
var form = FormApp.openById(FORM_ID);
var items = form.getItems(FormApp.ItemType.LIST);
for(var i in items){
Logger.log('id: ' + items[i].getId() + ' title: ' + items[i].getTitle());
}
}
PageBreakItem
A layout item that marks the start of a page. Items can be accessed or created from a Form.
PageNavigationType
An enum representing the supported types of page navigation. Page navigation types can be accessed from FormApp.PageNavigationType.
The page navigation occurs after the respondent completes a page that contains the option, and only if the respondent chose that option. If the respondent chose multiple options with page-navigation instructions on the same page, only the last navigation option has any effect. Page navigation also has no effect on the last page of a form.
Choices that use page navigation cannot be combined in the same item with choices that do not use page navigation.
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
var pageBreak = form.addPageBreakItem();
// Set some choices with go-to-page logic.
var rightChoice = item.createChoice('Vanilla', FormApp.PageNavigationType.SUBMIT);
var wrongChoice = item.createChoice('Chocolate', FormApp.PageNavigationType.RESTART);
// For GO_TO_PAGE, just pass in the page break item. For CONTINUE (normally the default), pass in
// CONTINUE explicitly because page navigation cannot be mixed with non-navigation choices.
var iffyChoice = item.createChoice('Peanut', pageBreak);
var otherChoice = item.createChoice('Strawberry', FormApp.PageNavigationType.CONTINUE);
item.setChoices([rightChoice, wrongChoice, iffyChoice, otherChoice]);
You can follow the sample create by Google and the implementation used in
Mogsdad's answert to further understand the flow.
I've added his code snippet:
function createForm() {
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
item.setTitle('Do you like Food')
var page2 = form.addPageBreakItem()
.setTitle('Page 2')
var item2 = form.addTextItem();
item2.setTitle('Why do you like food?')
var page3 = form.addPageBreakItem()
.setTitle('Page 3')
var item3 = form.addTextItem();
item3.setTitle("Why don't you like food?")
item.setTitle('Question')
.setChoices([
item.createChoice('Yes',page2),
item.createChoice('No',page3)
]);
}
So I was in the presumption that this function
button.onclick = exampleFunk;
would give me a handler on each button when I click them, but it doesn't. When replacing it with:
button.onclick = alert("bananas");
I'm getting alerts at page onload. The problem is already solved with this:
button.setAttribute("onclick", "removeIssue(this)");
Out of curiousity... What's going on?
edited layout of post
EDIT
var issues = [];
window.onload = function () {
//alert("venster geladen");
issuesToList()
}
function issuesToList(data) {
/*alert(
"array length is " + data.issues.length + "\n" +
"total_count is " + data.total_count + "\n" +
"limit is " + data.limit + "\n" +
"offset is " + data.offset + "\n" + ""
);*/
for (i = 0; i < data.issues.length; i++) {
issue = data.issues[i];
createIssue(issue);
}
}
function createIssue(issue){
var id = issue.id;
var tracker = issue.tracker;
var status = issue.status;
var priority = issue.priority;
var subject = issue.subject;
var description = issue.description;
var assignee = issue.assignee;
var watchers = issue.watchers;
var ticket = new Issue(id, tracker, status, priority, subject, description, assignee, watchers);
issues.push(ticket);
var button = document.createElement("button");
button.innerHTML = "-";
button.onclick = function (){ alert("bananas")};
//button.setAttribute("onclick", "removeIssue(this)");
var item = document.createElement("div");
item.setAttribute("id", id);
item.appendChild(button);
item.innerHTML += " " + subject;
var container = document.getElementById("container");
container.appendChild(item);
}
function removeIssue(e){
var key = e.parentNode.getAttribute("id");
var count = issues.length;
if(confirm("Confirm to delete")){
for(i=0; i<count; i++){
if (issues[i].id == key ){
issues.splice(i,1);
var element = document.getElementById(key);
element.parentNode.removeChild(element);
}
}
}
}
function Issue(id, tracker, status, priority, subject, description, assignee, watchers){
this.id = id;
this.tracker = tracker;
this.status = status;
this.priority = priority;
this.subject = subject;
this.description = description;
this.assignee = assignee;
this.watchers = watchers;
}
EDIT
<body>
<h1>List of Issues</h1>
<div id="container"></div>
<script src="http://www.redmine.org/issues.json?limit=10&callback=issuesToList"></script>
</body>
You need to mask the alert in a function:
button.onclick = function (){ alert("bananas")};
As such:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
btn.onclick = function() {alert("bananas")};
document.body.appendChild(btn);
Whats going on?
You alert() is executed on page load because its a function call. When the execution of your script reaches that line your assignment
button.onclick = alert("bananas");
is actually executing the alert statement and not assigning it to button.onclick
You can bind arguments to the function so that it returns with the function you want it to call using your arguments (with additional arguments passed later added on to the end). This way doesn't require writing extraneous code (when all you want to do is call a single function) and looks a lot sleeker. See the following example:
button.onclick = alert.bind(window, "bananas");
An unrelated example of how it works in your own code is like this:
var alert2 = alert.bind(window, 'Predefined arg');
alert2(); // 'Predefined arg'
alert2('Unused'); // 'Predefined arg'
For IE, this requires IE9 as a minimum. See MDN for more information.
EDIT: I've looked closer at your code and there was one significant change that was needed for it to work... You cannot add onto the innerHTML when you've added JavaScript properties to a child element. Changing the innerHTML of the parent element will convert your element into HTML, which won't have the onclick property you made before. Use element.appendChild(document.createTextNode('My text')) to add text dynamically.
See a functioning example here: http://jsfiddle.net/2ftmh0gh/2/
I am having trouble removing the child of a child of an object created using JS.
Basically once I create a comment object I appendChild(replyBox) to it. Inside the replyBox there is a cancel button which is supposed to completely delete the replyBox.
Here is the code :
function Comment(message){
var self = this;
var message = message;
var comment = document.createElement("li");
comment.id = "comment";
comment.style = "display: none;";
comment.textContent = message;
createButtons(comment);
var parent = document.getElementById("wall");
parent.appendChild(comment);
return comment;
}
function deleteComment(comment){
var parent = document.getElementById("wall");
parent.removeChild(comment);
}
function newReply(comment){
var buttons = comment.getElementsByTagName("input");
buttons.item(0).disabled="disabled";
var replyBox = document.createElement("div");
replyBox.id="replyBox";
var replyTxt = document.createElement("input");
replyTxt.type="text";
replyTxt.value="Write a reply";
replyTxt.onfocus = "if(this.value==this.defaultValue) this.value='';" ;
replyTxt.onblur="if(this.value=='') this.value=this.defaultValue;";
replyBox.appendChild(replyTxt);
createButtons(replyBox);
comment.appendChild(replyBox);
}
function createButtons(parent){
var button = document.createElement("input");
button.type = "submit";
if(parent.id=="comment"){
var reply = button.cloneNode();
reply.value = "reply";
reply.addEventListener("click", function(){newReply(parent)},false);
parent.appendChild(reply);
var deleteBtn = button.cloneNode();
deleteBtn.value = "delete";
deleteBtn.addEventListener("click", function(){deleteComment(parent)},false);
parent.appendChild(deleteBtn);
}
else{
var submitBtn = button.cloneNode();
submitBtn.value = "submit";
//reply.addEventListener("click", function(){newReply(parent)},false);
parent.appendChild(submitBtn);
var cancel = button.cloneNode();
cancel.value = "cancel";
cancel.addEventListener("click", function(){cancel(parent)},false);
parent.appendChild(cancel);
}
}
function cancel(replyBox){
replyBox.parentNode.removeChild(replyBox);
}
cancel.addEventListener("click", function(){cancel(parent)},false);
Which cancel is which? You have an object called cancel as well as a function with the same name. Try renaming one.
I see a problem here:
comment.id = "comment";
If you're setting all IDs of the comment elements to comment, the DOM may be getting confused.