JavaScript remove li element by button - javascript

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>

Related

How can I create an ol with a li element so that if I create a text node, it can be adding with ordered numbers on the same line in JS

How can I make this code work well with the list printing the result on the same line.
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
mainBody.innerHTML = '<li></li>'
const text = document.getElementById("toDo").value;
const myText = document.createTextNode(text);
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Few things:
You overwrite the contents of the previous list when you do mainBody.innerHTML = '<li></li>'.
It is not semantically correct to add a text node to an ordered list. Instead, create a li element and append the text node to the li.
Try this instead:
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
const text = document.getElementById("toDo").value;
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(text));
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Added few things:
remove the value of input when button is clicked
check if length of input is greeter then 1
event listener when enter key is pressed
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button id="btn">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
var input = document.getElementById("toDo")
if(input.value.length < 1 || input.value.replaceAll(" ", "") < 1) return; // check if the input value length is greeter then 1 character
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(input.value));
mainBody.appendChild(myText);
input.value = ''; // clear the value input
}
document.getElementById("btn").addEventListener("click", submitText); // save the input value when button is clicked
document.getElementById("toDo").addEventListener('keypress', function (e) {
if (e.key === 'Enter') submitText();
}); // save the input value when enter key is pressed
</script>
</body>
</html>
Change
mainBody.innerHTML = '<li></li>'
to
mainBody.innerHTML += '<li></li>'

The button is not added via a variable in the TEXT method

I'm doing a task sheet. I dynamically add items to the list along with the delete button, but the button is not displayed. Why?
I can certainly write the code differently, but why does this code not work?
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var del = $("<input type='button' value='X'></input>").text();
//var item = $("<li></li>").text(text + del);
var item = $("<li></li>").text(text + del); // DONT WORK! WHY?
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>
With this code I want to achieve this result. But I can not. Who will help explain where I'm wrong?
<li>Some Text <input type='button' value='X'></input></li>
In your code $("<input type='button' value='X'></input>").text() returns undefined.
Try this:
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var delHTML = "<input type='button' value='X'></input>";
var item = $("<li></li>").html(text + delHTML);
$("ul").append(item);
}
});
});
Your issue stemmed from not appending the delete button to the list item reference. As it's written I can add a list item to the ul but the button's delete button element was never attached to the list item.
Second, I removed .text() from var del = $("<input type='button' value='X'></input>").text();.
Here's my full solution.
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
// Creating elements
var deleteBtn = $("<input type='button' value='X'></input>");
var item = $("<li></li>").text(text);
// Appending elements
item.append(deleteBtn);
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>

how to count check checkboxes in a specific div JAVASCRIPT

I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head>!), here is the code :
HTML
<div class="changer">
<label><input id="mode" type="checkbox" name="mode" value="Mode" onclick="mode()" />Mode</label><br />
<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />
<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />
<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />
</div>
</head>
<body>
<div id="text">
</div>
</body>
<button id="send" onclick="send()">Envoyer</button>
Javascript
function joueurs() {
if((document.getElementById("joueurs").checked == true)) {
joueursall.style.display = 'inline';
text.style.display = 'inline';
}
else {
if((document.getElementById("mode").checked == true)) {
modeall.style.display = 'none';
document.getElementById('mode').checked = false;
}
joueursall.style.display = 'none';
text.style.display = 'none';
}
}
document.getElementById("playerlist").addEventListener("change", function() {
var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
document.getElementById("text").innerHTML = html;
});
Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div
I tried multiple things but always return 0 or all the checkboxes...
In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.
var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);
CodePen Demo
If you want to alert only the length of the checked checkboxes, you can query them like this:
var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);
CodePen Demo
when you click on the button, it will alert the number of checked boxes

Checkbox select deselect all and perform function

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

DOM created Delete Button not working properly

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);
}
);

Categories

Resources