Dynamically created form called via onclick disappears immediately Javascript - javascript

I have dynamically created a button in my Javascript function and called another function onclick, as shown below.
streambtn = document.createElement("button");
streambtn.setAttribute("onclick","createattribute()");
The createattribute() method opens a subdivision within the dynamically created form and this function is as follows.
function createattribute() {
inputval.innerHTML = "Provide a Stream name and click to add attribute-type pairs to yours stream.";
var input = document.createElement("input");
input.type = "text";
input.placeholder="Attribute name";
input.id="attr"+attrID;
input.className = "attr-textfield-style";
inputval.appendChild(input);
//Display the drop down menu
var newDiv=document.createElement('div');
var html = '<select>', attrtypes = typeGenerate(), i;
for(i = 0; i < attrtypes.length; i++) {
html += "<option value='"+attrtypes[i]+"'>"+attrtypes[i]+"</option>";
}
html += '</select>';
newDiv.className="attr-combobox-style";
newDiv.id="type"+attrID;
newDiv.innerHTML= html;
inputval.appendChild(newDiv);
attrID++;
alert("attrname id: "+input.id+" attrtype id: "+ newDiv.id);
}
The inputval is a division within the dynamically created form where the newly created form elements from the createattribute() function will be appended to. But the issue that I'm facing right now, is that though the method is correctly called, the form(dynamically created form) immediately disappears in a split second once the streambtn is clicked. Once it is clicked, it displays the first line "Provide a Stream name and click to add attribute-type pairs to yours stream." in a flash and disappears. Is there a way to keep it onscreen and then hide it depending on any conditions(like after the user finishes entering the data corresponding to that newly opened form-> created via createattribute() method)?

Add type = "button" as <button> without type = "button" will act as submit button and over click of the submit buttopn, page will be unloaded.
streambtn = document.createElement("button");
streambtn.type = 'button';
streambtn.setAttribute("onclick","createattribute()");

Related

I want to use vanilla JS to remove the parent element of the button I'm pressing on click

I created a meme generator that accepts text and images and puts them all together. The generator creates a unique ID for each 'meme' and also adds buttons that show up on hover to "delete" the meme. I used vanilla JS to create this and therefore had to layer a few different child divs on top of one another: image, top text, bottom text using z-index.
I am struggling, however, to get the button to delete the parent div. I want to be able to click that delete button, and have the parent div deleted so that the button goes away, along with image and text. picture below + code snippets.
I attemped to do it with vanilla javascript, by adding a closeTheMeme function on click to each button:
let deleteBtns = document.getElementsByClassName('.delete');
function closeTheMeme (){
this.parentElement.parentElement.removeChild();
};
for(let i=0;i<deleteBtns.length;i++){
deleteBtns[i].addEventListener("click",closeTheMeme);
}
No errors on console...Including the rest of the JS below so you can see how the elements are created on click of the meme generator.
'use strict';
let count=0;
// SUBMIT FORM
document.getElementById('memeInput').addEventListener('submit',function(e){
count++;
//prevent default
e.preventDefault();
//set image, top, and bottom to variables we can work with
let bottomText = document.getElementById('bottomText').value;
createMeme();
})
function createMeme(){
//create a meme section with an ID of the number of times the button was clicked, and add it to the meme section
let meme = document.createElement("DIV");
document.body.appendChild(meme);
meme.setAttribute("id", "meme"+count);
//create an image, set that image to equal the link, give it an id based on form submits, set image.src equal to the link
let img = document.createElement("IMG");
img.setAttribute("id","image"+count);
let imageLink = document.getElementById('imageLink').value;
meme.appendChild(img);
document.getElementById("image"+count).src=imageLink;
//set top text variable equal to the ID of toptext. value(form submission)
let topText = document.getElementById('topText').value;
let top = document.createElement('DIV');
top.setAttribute("id","topText"+ count);
meme.appendChild(top);
top.innerHTML = topText;
//set bottom text variable equal to the ID of toptext.value form submission
let bottomText = document.getElementById('bottomText').value;
let bottom = document.createElement('DIV');
bottom.setAttribute("id","bottomText" + count);
meme.appendChild(bottom);
bottom.innerHTML = bottomText;
//add a button that deletes the meme in the same way as above
let deleteButton = document.createElement("BUTTON");
deleteButton.classList.add("delete");
deleteButton.innerHTML = "Delete";
meme.appendChild(deleteButton);
//styling and position
meme.classList.add("meme");
top.classList.add("topWords");
bottom.classList.add("bottomWords");
};
let deleteBtns = document.getElementsByClassName('.delete');
function closeTheMeme (){
this.parentElement.parentElement.removeChild();
};
for(let i=0;i<deleteBtns.length;i++){
deleteBtns[i].addEventListener("click",closeTheMeme);
}
You select the buttons when the page loads. You created no buttons so it is not possible for it to work since there is nothing to bind an event to.
Since you are making the buttons, add the event there.
const deleteButton = document.createElement("BUTTON");
deleteButton.addEventListener("click", function () {
this.closest("div").remove();
});
Other option is event delegation
document.body.addEventListener("click", function (e) {
const btn = e.target.closest(".delete");
if (btn) btn.closest("div").remove();
});

add event to the radio button created using createElement in angular

I had created the dynamic radio button to be added to the html in angular ,just wanted to how can i add a click event to it along with the function name that should be invoked when click occurs and pass parameter to that function as well,below is the code that i'm trying out
for (let c in consult.value.rabies) {
for(let i in consult.value.rabies[c].choices){
const radio:HTMLInputElement = this.renderer.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.addEventListener("click")
const lbl = this.renderer.createElement("label");
lbl.innerHTML = consult.value.dance[c].types[i].text;
this.renderer.appendChild(this.div.nativeElement, radio)
this.renderer.appendChild(this.div.nativeElement,lbl)
}
}
event listener i want to create as followed radio.addEventListener("click","rabiesBuild(array)")
You can try -
const radioButton = document.querySelector('radio')[0]; radioButton.addeventListener("click","rabiesBuild(array)")

Event listener doesn't work after adding a new element

Basically, I have a text box where I write some text, click "Add Post", and a new post will be prepended to a list of other posts (similar to Twitter). Each of these posts has a 'delete' button.
For now, when I click delete on each posts, I have a console.log that just says, "TEST". And it works fine. However, after I add a post, meaning, a new element has been prepended, the event listener stops working, even for the existing 'delete' buttons (not just the newly added one).
This is how I wrote the event listener for the delete.
for(var i = 0; i < deleteDOM.length; i++) {
deleteDOM[i].addEventListener("click", deleteEntryCont);
}
...Where deleteEntryCont is just a function that console logs "TEST" for now.
deleteDOM is the variable for document.getElementsByClassName("delete") and is just a node list.
Here's the part where a new 'post' is added:
entryList.forEach(function(entry) {
var entryItemDOM = document.createElement("li");
var entryTextDOM = document.createElement("p");
var metaWrapperDOM = document.createElement("div");
var timeStampDOM = document.createElement("span");
var deleteDOM = document.createElement("span");
// Create entry wrapper & class names
entryItemDOM.className = "entry";
entryItemDOM.className += ` ${entry.mood}-entry`;
entryItemDOM.id = entry.id;
// Insert entry at the top of the stack
domEl.entriesDOM.insertBefore(entryItemDOM, domEl.entriesDOM.firstChild);
entryItemDOM.appendChild(entryTextDOM);
entryTextDOM.innerHTML = entry.text;
entryItemDOM.appendChild(metaWrapperDOM);
metaWrapperDOM.className = "overflow-hidden";
metaWrapperDOM.appendChild(timeStampDOM);
timeStampDOM.className = "timestamp";
timeStampDOM.innerHTML = entry.timeStamp;
metaWrapperDOM.appendChild(deleteDOM);
deleteDOM.className = "delete";
deleteDOM.innerHTML = "Delete";
});
Where entryList is an array of objects that this above code renders in HTML.
What could be the issue?
As discussed in the comments, you're only adding the event listeners when the page is loaded, which means it's only added to the posts that are visible at the time. You need to add the listener separately to each new post you create:
metaWrapperDOM.appendChild(deleteDOM);
deleteDOM.className = "delete";
deleteDOM.innerHTML = "Delete";
deleteDOM.addEventListener('click', deleteEntryCont);

How to get this code to work by calling event on Div instead of button?

I wrote a little web app todo list. I am trying to run an eventListener on my customizeDiv but for some reason the code won't work.
Description of program:
This todo list will allow the user to add tasks to a list, but the code provided has to do with customization of the list. The user can click 'customize list' which will then create another button called 'List Color' (the only option right now). Once clicked an input field will appear allowing the user to enter a color, changing the background color of the body element.
Right now I have nested event listeners but I heard this is not good practice. This program currently works using nested event listeners. I am trying to avoid that and also am trying to find out why I can't get it to work when using an event listener on the customizeDiv instead of the customizeButton initially. Here are all declared variables being used:
//Div containing all customization buttons
const customizeDiv = document.getElementById('customization');
/*This button allows the user to select what part of the list they want
to customize, right now it only contains one button 'List Color'. When
clicked, the user will enter a color into an input text field, changing
the background-color of the body.*/
const customizeButton = document.createElement('button');
customizeButton.textContent = 'Customize your list';
customizeDiv.appendChild(customizeButton);
//Event listener on the customization button
customizeButton.addEventListener('click', function() {
const colorButton = createButtonOnMenu('button', 'textContent', 'List Color');
customizeDiv.removeChild(customizeDiv.firstChild);
customizeDiv.appendChild(colorButton);
//Event listener when user selects to change list color
colorButton.addEventListener('click', function() {
//Create the necessary elements to create new text submit.
const colorForm = document.createElement('form');
const colorInput = document.createElement('input');
const colorChangeButton = document.createElement('button');
colorChangeButton.type = 'submit';
colorChangeButton.textContent = 'Submit Color';
colorChangeButton.id = 'setColor';
colorInput.type = 'text';
colorInput.placeholder = 'Enter Color';
colorInput.id = "colorInput";
colorForm.id = "colorForm";
colorForm.appendChild(colorInput);
customizeDiv.appendChild(colorForm);
customizeDiv.removeChild(colorButton);
customizeDiv.addEventListener('submit', (e) => {
e.preventDefault();
const body = document.getElementById('myBody');
if(colorInput.value === ''){
alert('Please enter a valid color!');
}else {
body.style.backgroundColor = colorInput.value;
if(colorForm.parentNode){
customizeDiv.removeChild(colorForm);
customizeDiv.appendChild(customizeButton);
}
}
});
});
});

Html Code not working properly while generated with JavaScript

I am trying to impliment the IN Place Editing functionality using JQuery.
Here is the code
editinplace.js
$(document).ready(function() {
//When div.edit me is clicked, run this function
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}
});
});
ButtonClickFunction.js
function ADDRADIOBUTTON(){
//Creating the div Tag
var answer_div = document.createElement("div");
answer_div.setAttribute("class", "answer");
answer_div.id = "answer_div_"+counter;
// Creating the Radio button tag
var answer_tag = document.createElement("input");
answer_tag.setAttribute("type", "radio");
answer_tag.id = "answer_tag_"+counter;
answer_tag.setAttribute("name", answer_div.id);
// Creating the Label Tag
var radio_label_tag = document.createElement("label");
radio_label_tag.setAttribute("for", answer_tag.id);
//Creating the label
var In_Place_Edit_div = document.createElement("div");
In_Place_Edit_div.setAttribute("class", "editme");
var In_Place_Edit = document.createTextNode("label");
In_Place_Edit_div.appendChild(In_Place_Edit);
radio_label_tag.appendChild(In_Place_Edit_div);
// Adding Radio button dot on the div and screen actually
answer_div.appendChild(answer_tag);
//Adding the Label here on the right of radio button.
answer_div.appendChild(radio_label_tag);
// Adding Answer div to the main div
var element=document.getElementById("divid_"+counter);
element.appendChild(answer_div);
}
and the index.php file includes these two JS files along with jquery-1.8.2.min.js
<script language="javascript" src="js/jquery-1.8.2.min.js"></script>
<script language="javascript" src="js/editinplace.js"></script>
<script type="text/javascript" src="js/ButtonClickFunction.js"></script>
What I am trying to do is create a radio button with label besides it and the label can be edited when we click on it. Now the problem here is that when I use the Code
<div class="editme">Please click me!!</div>
directly in the index.html page it works fine but when I try to generate the same line of code dynamically as I shown in ButtonClickFuction.js file it Does not work. What might be the problem ?
After crerating the HTML element dynamically you must bind the click function once more.Otherwise it wont work.Just call the click function after dynamic creation of the
< div class="edttime">Please click me!!.Otherwise click wont work for the newly created div with class edttime.
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}

Categories