How to delete text box along with button in JavaScript - javascript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button

You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>

This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".

Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

Related

can javascript version of print be inserted inside the code of a Div?

I have a form that adds and subtracts a smaller form when user clicks on add or subtract users button.
what I want to do is add a +1 every time the user hits the add button to a ID tag inside the div tag.. confusing yes I know
say this is the original tag:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
now say the user clicks on a add button and a new form will pop up below the current form and using a print or echo version of javascript this would be the new code created for the div using .append(html) or something along those lines too this:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
<div id="formwrap" class="test2" name="test2">im a form in this formwrap</div>
and so on as u can see next the 2 would change to a 3 if someone where to click the add button
<div id="formwrap" class="test(+1 code would go here)" name="test(+1 code would go here)">im a form in this formwrap</div>
So before I code is this even possible? I want to be able to style the smaller form differently and I want the phpmailer to be able get retrieve all the data depending on how many clicks they do. and adding a +1 too each of the tags would do both goals.
It is possible using data attributes.
See: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
You would do something like this
var count = 0
var formwrap = document.getElementById('formwrap');
formwrap.dataset.name = "aName" + count
// increment count on click
You can use jquery for this when user click on add button you have to increment the value of count like this ...
var count = 0;
$("button").on("click", function () {
var html = '<div id="formwrap'+count+'" class="test'+count+'"
name="test'+count+'">im a form in this formwrap</div>';
count++;
$(div).append(html);
});
this way you can do this.
//Create a private counter var
const counter = (function() {
var formCount = 0;
return {
value: () => formCount,
increment: () => ++formCount
}
})();
//A function that will generate a "form" element
const ID_PREFIX = 'formwrap_';
const generateFormEl = () => {
let el = document.createElement('div');
el.setAttribute('id', `${ID_PREFIX}${counter.increment()}`);
el.setAttribute('class', 'test');
el.setAttribute('name', 'test');
el.appendChild(document.createTextNode(`ID: ${el.getAttribute('id')}`));
return el;
};
//Store your DOM elements in some vars
const forms = document.querySelector('#forms');
const btn = document.querySelector('[type="button"]');
//Add a form element to the DOM on click
btn.addEventListener('click', () => {
const form = generateFormEl();
forms.appendChild(form);
});
<div id="container">
<input type="button" value="Add a form" />
<div id="forms"></div>
</div>

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id.
The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.
document.getElementById("addRow").onclick = function () {
var newCustomerlbl = document.createElement("label");
newCustomerlbl.innerHTML = "Cutomer Name: ";
var newCustomertxt = document.createElement("input");
newCustomertxt.setAttribute("type", "text");
var delBtn = document.createElement("input");
delBtn.setAttribute("type", "button");
delBtn.setAttribute("value", "Delete");
delBtn.setAttribute("id", "btnDelete");
var newArticle = document.createElement("article");
newArticle.appendChild(newCustomerlbl);
newArticle.appendChild(newCustomertxt);
newArticle.appendChild(delBtn);
var customerSection = document.getElementById("customerRecords");
var customerArticles = customerSection.getElementsByTagName("article");
for (var i = 0; i < customerArticles.length; i++) {
var lastDigit = i + 1;
var newArticleValue = "article" + lastDigit;
newArticle.setAttribute("id", newArticleValue);
}
customerSection.appendChild(newArticle);
}
Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.
Here is the my jsFiddle code.
If you don't want to use jQuery you can add event listeners to your buttons:
delBtn.addEventListener('click', function () {
this.parentElement.remove();
}, false);
https://jsfiddle.net/3nq1v5e1/
You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?
If you are using JQuery, things get real simple, just add something like
$(document).on('click','.btnDelete', function(){
$(this).closest('article').remove();
});
(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).
If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created
newArticle.appendChild(delBtn);
delBtn.onclick = function(.....
etc.

Get value of appended textarea

i append a textarea with a button
$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");
After that , i'm writing new texts into textarea and trying to get new writed value inside from textarea with this on click function ;
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
});
But it says that this an "empty string" , if i add text area with a value like <textarea id="myTextarea">some text</textarea> my fucntion works and gives me "some text" but if i edit textarea and click sendReply button (my on click function), it is still gives me "some text" , it don't change
How can i get edited textarea value after apppend a textarea?
You have an . in .sendReply while appending the HTML
You just need to remove . from .sendReply
Use
<div class='sendReply btn btn-default'>my button</div>"
As you are using Event delegation your jQuery will work.
As you are adding textarea with same ID multiple times? $("#myTextarea").val() will always show value of first textarea with id myTextarea. You can use a common class and then use prev() to select the textarea
See example
$(document).ready(function() {
$(document).on('click', '.sendReply', function() {
var myNewText = $(this).prev(".myTextarea").val();
alert(myNewText);
});
for (var i = 0; i < 5; i++) {
$(".mydiv").append("<textarea class='myTextarea'>some text</textarea><div class='sendReply btn btn-default'>my button</div>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='mydiv'></div>
It should be
$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");
then
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
});
dont use dot(.) for the classname..
Instead using div .. use some standard to code up .. you can make it has button .. here is the code
<div class="mydiv"></div>
$(".mydiv").append("<textarea id='myTextarea'></textarea><input type='button' class='sendReply btn btn-default' value='my button'></input>");
jQuery(document).on('click','.sendReply', function () {
var myNewText = $("#myTextarea").val();
console.log(myNewText);
alert(myNewText);
});
JSFIDDLE

onClick replace javascript element, with new javascript element

What I am trying to figure out is how to make a button, that when you click, will replace itself with a textbox. I found this code on the W3Schools website, and can't figure out how to put javascript (or HTML) elements in.
<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<p id="demo">Visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace("Microsoft", "W3Schools");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
<input type="text" name="textbox" value="textbox"><br>
In the end I want to be able to replace a button with the textbox I put outside the html tags
I would not suggest you the innerHTML replacement method.
Here are the steps where you can use replaceChild
Get the parent node of the selected element
use replaceChild
Here the code
// create the new element (input)
var textBox = document.createElement("input");
textBox.type = "text";
// get the button
var button = document.getElementById("demo");
// reference to the parent node
var parent = element.parentNode;
// replace it
parent.replaceChild(textBox, button);
On older browser you probably need a slighlty different solution.
var parent = button.parentNode;
var next = button.nextSibling;
// remove the old
parent.removeChild(button);
// if it was not last element, use insertBefore
if (next) {
parent.insertBefore(textBox, next);
} else {
parent.appendChild(textBox);
}
I ended up finding a code that works off of http://www.webdeveloper.com/forum/showthread.php?266743-Switch-Div-Content-Using-Javascript

Button onclick only checkes the first appended checkbox

With the script below I append 3 elements when the append button is clicked.
a checkbox
input text field
delete button
For now, when the delete button is clicked the checkbox is checked,
but when I append another (let's call it a group) three items, the script doesn't work.
Can anybody explain how I can link the elements in some sort of way.
So that every time I click the append button the elements are linked to the elements that were created at the same time the same on click.
Thank you so much in advance
<html>
<head>
<script language="Javascript">
function append()
{
var cb = document.createElement("input");
cb.type = "checkbox";
cb.id = "id"
cb.checked = false;
var textfield = document.createElement("input");
var delbtn = document.createElement("input");
delbtn.type = "button";
delbtn.value = "remove";
delbtn.onclick= function(){remove()}
document.getElementById('append').appendChild(cb);
document.getElementById('append').appendChild(textfield);
document.getElementById('append').appendChild(delbtn);
}
function remove()
{
id.checked = true;
}
</script>
</head>
<body>
<div id="append"></div>
<input type="button" value="append" onClick="javascript:append()"/>
</body>
</html>
Each time you append a new checkbox, you're running
cb.id = "id"
This is problematic, since elements should have unique ids.
Also, you're referencing the element by its id in the global scope:
id.checked = true;
You should use the standard document.getElementById() instead.

Categories

Resources