DOM created Delete Button not working properly - javascript

Ok here is what I was trying to do... Create a delete button along with edit by using DOM while creating a paragraph. But delete button always seems to be deleting first paragraph instead of deleting the corresponding paragraph.. here's my code:
Javascript:
function writePara()
{
var comment = document.getElementById("usrinput").value;
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
document.getElementById("updateDiv").appendChild(newParagraph);
var button = document.createElement("button");
var Btext=document.createTextNode("EDIT");
button.appendChild(Btext);
document.getElementById("updateDiv").appendChild(button);
button.onclick =
(
function()
{
var edit = prompt("Type to edit", "");
newParagraph.innerHTML = edit;
}
);
var button2 = document.createElement("button");
var Btext2=document.createTextNode("DELETE");
button2.appendChild(Btext2);
document.getElementById("updateDiv").appendChild(button2);
button2.onclick =
(
function ()
{
var items = document.querySelectorAll("#updateDiv p");
if (items.length)
{
var child = items[0];
child.parentNode.removeChild(child);
}
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);
addBr();
}
And the HTML:
<body onload="radio()">
<div id="paraButton" align="left">
<form><h3>Enter your Paragraph content here:</h3>
<textarea cols="20" rows="10" id="usrinput">Enter your texts here...</textarea>
</form>
<form id="one"><input type="button" value="Apply" onclick="writePara()"/></form>
<div id="updateDiv" name ="update"><h1>Space for Paragraph</h1> </div>
</div>
<div id="radioButton">
<h3>Type your radio button here:</h3>
<input type="text" name="option" id="option" value="Example 1" />
</br></br>
<button id="AddButton">Add</button>
<button id="RemoveButton">Remove</button>
</br></br></br></br></br></br></br></br>
<div id="updateDivRadio"><h1>Space for Radio Button</h1></div>
</div>
</body>
P.S: the radio() function is working fine this is just a segment that I'm having problem with.

Ok I got it working with the help of others so decided to share here...
Changing button2.onclick to this works.
button2.onclick =
(
function ()
{
newParagraph.parentNode.removeChild(newParagraph);
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);

Related

Trying to check for empty value in input

I have an input box that changes another paragraph in my site with JavaScript. It works flawlessly, except for the fact that when I enter nothing in the input, it blanks out the paragraph.
I don't want this to happen. I've tried almost every piece of code I've found online to fix this issue but nothing has worked.
<div class="tasklist">
<p id="task1" style="color:#d3d3a3">You don't have any tasks.</p>
</div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
element.innerHTML = (value);
document.getElementById("task1").style.color = "white";
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();" onclick="changeColor()">+ Add</button>
<div id="tasklist">
<p id="msg" style="color:red">You don't have any tasks.</p>
</div>
<br>
<script>
const element = document.getElementById("msg");
element.style.display = "none";
function add() {
let value = document.getElementById("task").value;
if (value && value.trim() != "") {
document.getElementById("task").value = "";
element.style.display = "none";
const taskContainer = document.getElementById('tasklist');
const task = document.createElement('p');
task.textContent = value;
taskContainer.append(task)
} else {
element.style.display = "block";
}
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="add();">+ Add</button>
First of all add value checker - it will prevent from setting innerHTML as "".
Secondly i think You want to add element with another task, not removing older ones.
use .append() to add at the end of parent or prepend() to add at the begginning of parrent.
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function changeColor(){console.log("color")};
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.append(
Object.assign(
document.createElement("p"),
{textContent:value}
)
);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();changeColor()" >+ Add</button>
if You rather want to replace Your first child then
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.replaceChild(Object.assign(document.createElement("p"),{textContent:value}),element.firstChild);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue()" >+ Add</button>

JavaScript remove li element by button

Please help to configure the button on removing dynamic elements.
I have an code : https://www.w3schools.com/code/tryit.asp?filename=G2T2WSPSDUVS
Code :
<!DOCTYPE html>
<html>
<body>
<div>
<input type="checkbox" id="coffee" name="coffee" checked>
<label for="coffee">Coffee</label>
</div>
<div>
<input type="checkbox" id="gym" name="gym">
<label for="gym">Gym</label>
</div>
<div>
<input type="checkbox" id="rose" name="rose">
<label for="rose">Rose</label>
</div>
<button onclick="myFunction()">Try it</button>
<ul id="myList"></ul>
<script>
function myFunction() {
var node = document.createElement("LI");
var checkBoxCoffe = document.getElementById("coffee");
var checkBoxGym = document.getElementById("gym");
var checkBoxRose = document.getElementById("rose");
var textnode = document.createTextNode("");
if (checkBoxCoffe.checked == true){
textnode.textContent=textnode.textContent+"Coffee; "
}
if (checkBoxGym.checked == true){
textnode.textContent=textnode.textContent+"Gym; "
}
if (checkBoxRose.checked == true){
textnode.textContent=textnode.textContent+"Rose; "
}
var button = document.createElement("button");
button.innerHTML = "Remove";
node.appendChild(textnode);
node.appendChild(button);
document.getElementById("myList").appendChild(node);
}
</script>
</body>
</html>
How I can do that each button will remove exectly selected li element?
everything is working only remove button still need to do
thanks
add onclick event to button before node.appendChild(button);
button.onclick = function(){
button.parentElement.remove()
return;
};
Here is something i tried. (Note : I will suggest you to use something like `jquery' which will ease out many things.
document.getElementById('add').addEventListener('click',function(){
addItems();
});
function addItems(){
var parent = document.createElement('div');
var text = document.createElement('input');
text.innerText = "Click button";
var button = document.createElement('button');
button.className = "btn";
button.innerText = "Click";
parent.appendChild(text);
parent.appendChild(button);
// this is something you are looking for.
button.addEventListener('click',function(){
this.parentNode.remove();
});
document.getElementById('test').appendChild(parent);
}
<div id="test">
</div>
<button id="add"> Add more
</button>
Happy Coding!
you can try this code
in this code i create simple removeli function on remove button.
button.onclick = removeli;
function removeli()
{
document.getElementById("myList").removeChild(node);
}
Register the click event to the <ul> and then delegate the click event to the actual button clicked (event.target). Details commented in demo
// Register click event to button#add
document.getElementById('add').onclick = addItem;
// Reference <ul>
var list = document.getElementById('list');
function addItem(e) {
// Get all checked checkboxes
var chx = document.querySelectorAll('input:checked');
// Clear list
list.innerHTML = '';
// Loop through the checked checkboxes
for (let i = 0; i < chx.length; i++) {
// Create a <li>
var li = document.createElement('LI');
// Set <li> text to the checked checkbox label text
li.textContent = chx[i].nextElementSibling.textContent;
// Append a button to <li>
li.insertAdjacentHTML('beforeend', ` <button>×</button>`);
// Append <li> to <ul>
list.appendChild(li);
}
}
// Register click event to <ul>
list.onclick = removeItem;
function removeItem(e) {
// Reference the clicked tag
var tgt = e.target;
// if the clicked tag is a button...
if (tgt.tagName === "BUTTON") {
// Find the closest <li> to the clicked button and remove it
tgt.closest('li').remove();
}
// otherwise just terminate function
return false;
}
<!DOCTYPE html>
<html>
<body>
<div>
<input type="checkbox" id="coffee" name="coffee" checked>
<label for="coffee">Coffee</label>
</div>
<div>
<input type="checkbox" id="gym" name="gym">
<label for="gym">Gym</label>
</div>
<div>
<input type="checkbox" id="rose" name="rose">
<label for="rose">Rose</label>
</div>
<button id='add'>ADD</button>
<ul id="list"></ul>
</body>
</html>

Remove parent div on button press

trying to create a dynamic button system to add/remove inputs on clicks. I have the addButton working but not the deleteButton. What am I missing?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
The problem is, that $(this) inside the delete button handler refers to the minus button. That minus button is not inside each of the items (It's at the top. and doesn't have a parent div), so you need to reference the element you want to delete another way. In my case below, I'm selecting the last <div> in $(wrapper):
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(wrapper).find('div:last').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Also you can do it with pure JS using child Nodes. :D
Sometimes pure JS is beater than JQ
Explanation:
remove is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use removeChild.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Try below solution, I care about the back end also because you have to send the data to back end developer so you have to give the array name for input fields such as name="person[]". anyway you can try this solution also.
$(document).ready(function(){
var static_html = '<input type="text" name="person[]" class="input_fields" />';
$("#plus").click(function(){
if($(".input_fields").length < 20 )
$("#dynamic_field_container").append(static_html);
});
$("#minus").click(function(){
if($(".input_fields").length > 1 )
$(".input_fields:last").remove();
else
alert("This is default field so u can't delete");
});
});
.input_fields{
display:block;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="fa fa-plus fa-4x" id="plus"> </span>
<span class="fa fa-minus fa-4x" id="minus"> </span>
<div id="dynamic_field_container">
<input type="text" name="person[]" class="input_fields" />
</div>

how to show user input in the body when a button is clicked

I'm trying to display a user input on a separate div, but only have it appear when a button is clicked. I think i have it set up but I'm just not sure how to display the input. can someone help me with how it can be done?
<script>
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function(){
console.log("Call has been set");
userinput.style.display = "block";
</script>
<input id="callerIDInput" type="text" value="" >
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Set the input value to the innerHTML of the div
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function() {
console.log("Call has been set");
userinput.innerHTML = document.getElementById('callerIDInput').value
})
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Use innerHTML of the DIV to set the value.
HTML
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt' onclick="Display()">CALL</button>
Javascript
function Display()
{
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
var callerIDInput = document.getElementById("callerIDInput");
console.log("Call has been set");
userinput.style.display = "block";
userinput.innerHTML = callerIDInput.value;
}

change text of div using javascript

i have a div tag where i entered sime text. now i want, as the user clicks on the button, a cursor should pop-up and user edit the text. as user clicks on save button the text should displays min the div tag inplace of old text..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" type="hidden" onclick="edit1();"/>
Div Tag
</div>
here i want to have a cursor when user clicks edit button and as user ebters text and clicks save the ' div tag ' text should get replaced by new text..
how this can be done using java script..
What you are doing makes no sense from either a technical or semantic view. Just use a textarea.
<textarea id="content" value="sample text" disabled="true" /></textarea>
<input type="button" id="edit" value="edit" onClick="edit()" />
<input type="button" id="save" value="save" onClick="save()" />
function edit() {
document.getElementById('edit').style.display = 'none';
document.getElementById('save').style.display = 'block';
document.getElementById('content').disabled = false;
}
function save() {
document.getElementById('save').style.display = 'none';
document.getElementById('edit').style.display = 'block';
document.getElementById('content').disabled = true;
}
#content {
width: 300px;
height: 200px;
}
#edit, #save {
padding: 2px;
width: 50px;
}
#save {
display: none;
}
Example here
// This sample code is with prompt (popup input) if you want to use textbox, the code to be replaced accordingly.
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" style='display:hidden' onclick="edit1();"/>
<div id="text1"> </div>
</div>
<script>
function button1()
{
document.getElementById ("btndiv").display = '';
}
function edit1()
{
var val = prompt ("Enter some value");
document.getElementById ("text1").innerHTML = val;
document.getElementById ("btndiv").display = 'hidden';
}
</script>
I suggest creating an internal div enclosing just the text, like this:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="editbtndiv" onclick="edit1();" value="edit"/>
<input type="button" id="savebtndiv" onclick="save1();" value="save"/>
<input type="text" id="inputdiv" style="display:none;" />
<div id="divtext"> Div Tag </div>
</div>
Then, to display the input field and hide the text:
var editObj = document.getElementById("editbtndiv");
editObj.style.display = "none";
var saveObj = document.getElementById("savebtndiv");
saveObj.style.display = "block";
var inputObj = document.getElementById("inputdiv");
inputObj.style.display = "block";
var txtObj = document.getElementById("divtext");
txtObj.style.display = "none";
Then user does his job, clicks save and you can hide the input field and show the text:
var editObj = document.getElementById("editbtndiv");
editObj.style.display = "block";
var saveObj = document.getElementById("savebtndiv");
saveObj.style.display = "none";
var inputObj = document.getElementById("inputdiv");
inputObj.style.display = "none";
var txtObj = document.getElementById("divtext");
txtObj.value = divObj.value;
txtObj.style.display = "block";

Categories

Resources