Javascript method to remove a specific field - javascript

I want to attach more than one field to a div along with a remove button. Something similar to Gmail file attaching methods if the user presses the remove button it should remove the specified p along with the button. But if I press the remove button it is not working properly I know the javascript array method is the problem but I am not able to understand where I am going wrong
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
<script>
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
document.getElementById("attach").appendChild(content);
document.getElementById("attach").appendChild(btn);
}
function remove(i){
var elem = document.getElementsByClassName('element');
elem[i].remove();
return false;
}
</script>
The working plunker is here.
http://plnkr.co/edit/eYhfN85FH4XabzE4rO4M?p=preview
What is going wrong here? How can I fix this?

A slightly different approach that simplifies your original example, is to take advantage of the function/closure you create for the button you create. In there, you can literally just reference the content and btn elements, and remove them directly
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.className = 'element';
btn.innerHTML = "Delete This element";
btn.onclick = function(){
content.remove();
btn.remove();
};
content.innerHTML = value;
var attach = document.getElementById("attach");
attach.appendChild(content);
attach.appendChild(btn);
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
That way, you don't have to worry about what index you're removing or anything

Here you go!
function attach() {
const attachEl = document.getElementById("attach");
const value = document.getElementById("text").value;
const contentEl = document.createElement("p"); // is a node
contentEl.className = "element";
// Insert text
const btnEl = document.createElement("button");
btnEl.innerHTML = "Delete This element";
const wrapperEl = document.createElement("div");
btnEl.onclick = function() {
attachEl.removeChild(wrapperEl);
};
attachEl.appendChild(wrapperEl);
wrapperEl.appendChild(contentEl);
wrapperEl.appendChild(btnEl);
contentEl.innerHTML = value;
}
#attach{
background-color: teal;
}
.element {
background-color: wheat;
}
<form name="create" action="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>

We should use a wrapper to wrap a p & button together so that when we initiate delete it deletes the complete wrapper
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
var wrapper = document.createElement('div');
wrapper.className="wrapper";
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
wrapper.appendChild(content);
wrapper.appendChild(btn);
document.getElementById("attach").appendChild(wrapper);
}
function remove(i){
var elem = document.getElementsByClassName('wrapper');
elem[i].remove();
return false;
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>

Related

Javascript button for todo list doesn't work

I'm trying to get my button for my To-do list to work for days now.. The button is not working but I can't figure out what the problem is. I don't want to use "onclick" in the html file I want to do the click event in the javascript file.
And then I have been trying to figure out how to get the To-do list to work with adding new tasks and being able to mark the task complete without removing it but it was harder than i thought.. I'd love to get some pointers! Appreciate it guys
var closebtn = document.getElementsByClassName("close");
function todolist(){
var li = document.createElement('li');
var btn = document.getElementById('my-button').onclick = function(){
var list = document.getElementById('list');
var input = document.getElementById('task').value;
var func = addEventListener('my-button');
var textnode = documentcreateTextNode(input);
li.appendChild(textnode);
if (input === ' '){
alert("write")
} else {
document.getElementById(list).appendChild(li);
}
document.getElementById('task').value = " ";
var thePanTag = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
thePanTag.className = "close";
thePanTag.appendChild(txt);
li.appendChild(thePanTag);
for (i = 0; i < closebtn.length; i++){
closebtn[i].onclick = function(){
var Div = this.parentElement;
Div.style.display = none;
}}}}
<body>
<h2>To-do list!</h2>
<div>
<input type="text" id="task" placeholder="Write task" />
<button id="my-button">Add task</button>
</div>
<ul id="list">
<li>kaa</li>
<li>baa</li>
<li>ss</li>
<li>aa</li>
<li>aaa</li>
</ul>
I removed the unnecessary code and be aware of using the correct onlick function.
Try this:
var closebtn = document.getElementsByClassName("close");
todolist();
function todolist(){
var li = document.createElement('li');
var btn = document.getElementById('my-button').onclick = function(){
var ul = document.getElementById("list");
var li = document.createElement("li");
var input = document.getElementById('task').value;
if(input!=''){
li.appendChild(document.createTextNode(input));
ul.appendChild(li);
}
}
}
<h2>To-do list!</h2>
<div>
<input type="text" id="task" placeholder="Write task" />
<button id="my-button">Add task</button>
</div>
<ul id="list">
<li>kaa</li>
<li>baa</li>
<li>ss</li>
<li>aa</li>
<li>aaa</li>
</ul>

remove each li item todo list using on click

I intended to make a todo list but I'm getting a problem that i wanna make a button that come inline in list item like so <li>my task</li><button>Delete</button>
but my delete button isn't deleting items correctly it only deletes one items and then start giving error
this is my code, please look here and also tell me what kind of mistakes I'm doing I'm very beginner in web development
<!DOCTYPE html>
<html>
<body>
<input type="text" placeholder="Enter Task" onfocus="this.value=''" id="myTask">
<button onclick="myFunction()">Try it</button>
<button onclick="deleteTask()">del it</button>
<ol id="myList">
</ol>
<script>
function myFunction() {
var node = document.createElement("LI");
var myTask = document.getElementById("myTask").value;
var textnode = document.createTextNode(myTask);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
var btn = document.createElement("input");
var abcElements = document.querySelectorAll('LI');
for (var i = 0; i < abcElements.length; i++){
abcElements[i].id = 'abc-' + i;
}
// node.setAttribute("id", "li1");
btn.setAttribute("type", "submit");
btn.setAttribute("value", "delete");
btn.setAttribute("id", "delete");
node.appendChild(btn);
btn.addEventListener('click', ()=>{
// console.log("OK");
document.getElementById("abc-0").parentNode.removeChild(document.getElementById("abc-0"))
})
}
function deleteTask() {
var i = 0;
var item = document.getElementsByTagName("LI")[i];
i++;
item.parentNode.removeChild(item);
}
</script>
</body>
</html>
So I just want to make a delete button with every list item as I click on Try it button
Some points to address:
Don't call a function myFuntion. Give it a descriptive name, like addTask
Don't create id-attributes with sequential numbers. That is almost never needed.
The initial HTML should not have a delete button, since it should associate with a list item.
Don't make the type of the delete button "submit". That only makes sense when you have a form element, and need to submit the form.
Don't give the created button the same id over and over again: that is invalid in HTML. id-attributes should have unique values. But again, it is rarely needed to assign an id to dynamically generated elements.
In an event listener you can use the event object to get the element on which the event was fired. Or you can use the this object in a function. But you can also reference the node variable that exists in the so-called closure.
function addTask() {
var node = document.createElement("LI");
node.textContent = document.getElementById("myTask").value;
var btn = document.createElement("button");
btn.textContent = "delete";
btn.addEventListener('click', () => node.remove());
node.appendChild(btn);
document.getElementById("myList").appendChild(node);
}
li > button { margin-left: 5px }
<input type="text" placeholder="Enter Task" onfocus="this.value=''" id="myTask">
<button onclick="addTask()">Add task</button>
<ol id="myList"></ol>
try something like this:
function myFunction() {
const li = document.createElement("li");
li.innerHTML = document.getElementById("myTask").value;
const button = document.createElement("button");
button.innerHTML = "delete";
li.appendChild(button);
button.addEventListener("click", () => li.parentNode.removeChild(li));
document.getElementById("myList").appendChild(li);
}

How to loop over dynamically generated input fields?

I am generating some input fields dynamically on my page, and I want to grab inputs from them to store in localStorage if this way works if not? suggest a way around, how can this be done? also how can i add a event listener to submit button ? followings are code have a look at it and give some suggestions/improvisations.
..
HTML
<div id="warnMessage"></div>
<div class="add"></div>
<div class="inputs">
<input
type="text"
maxlength="1"
id="inputValue"
/>
<button class="btn" type="button">+</button>
</div>
javascript
const div = document.querySelector(".add");
const add = document
.querySelector(".btn")
.addEventListener("click", addingInps);
function addingInps() {
const inputValue = parseInt(document.getElementById("inputValue").value);
if (isNaN(inputValue)) {
document.getElementById("warnMessage").innerText = "Enter Again";
document.getElementById("inputValue").value = "";
} else {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
for (let i = 0; i < inputValue; i++) {
const inp = document.createElement("input");
inp.type = "text";
inp.maxLength = "12";
inp.required = true;
inp.className = "inp";
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(inp);
form.appendChild(br.cloneNode());
div.appendChild(form);
document.querySelector("#inputValue").style.display = "none";
}
const sub = document.createElement("button");
sub.className = "subButton";
sub.type = "button";
sub.value = "button";
sub.textContent = "Submit"
form.appendChild(sub);
}
}
You are loop through an input ...not an array or nodelist.
It cant work
I think it would be easier if you appended an ID with every new input field you made
for(let i=0;i < inputValue;i++){
// create your element ipt
ipt.setAttribute("id","autogenerated_" + i);
}
and grab value based on id
document.getElementById("autogenerated_x").value();
about setting an event listener, I can't think any other way of the classic
btn.addEventListener("click", function(e){
// your functionality
});

Transferring iframe value to textarea

I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>

JavaScript onClick button adds textarea into particular div elements

I am obviously missing something. I need this addmore button to add textarea into the div for the particular question, not only the first one. I can make it complicate, but I hope there is an easy solution.
Fiddle
index.html
1.Question:<br/>
<textarea name="odg1" rows="1" cols="50" ></textarea><br/><div id="inner"></div><button type="button" name="addmore" onClick="addmore();">Add more</button>
<br/><br/>
2.Question:<br/>
<textarea name="odg2" rows="1" cols="50" ></textarea><br/><div id="inner"><button type="button" name="addmore" onClick="addmore();">Add more</button>
<br/><br/>
addmore.js
am = 1;
function addmore() {
var textarea = document.createElement("textarea");
textarea.name = "odg" + am;
textarea.rows = 1;
textarea.cols = 50;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner").appendChild(div);
am++;
}
This function demonstrates how to generate more element using jQuery:
var am = 1;
function addmore() {
var newText = $('<textarea />').attr('name','odg'+am).attr('rows',1).attr('cols',50);
var newBtn = $('<button />').attr('onclick','addmore()').html('add more');
$('body').append(newText);
$('body').append('<br />');
$('body').append(newBtn);
am++;
}

Categories

Resources