How to delete an element from an Array with Onclick? Javascript?

Asked

Viewed 486 times

0

i am with a code that, render the elements of the Array on the screen, and each element of the Array, has a button delete next door.

I wanted to know how to delete it from Array and consequently remove it from the screen and in place of the element that was excluded appear the element that was below it.

I have this code:

let pageCurrent = 0;
let elementsPerPage = 3;
let novoArray = [];
const observation = document.getElementById('obs');

const names = [
  {id:0, name:"Jean"}, 
  {id:2, name:"Ricardo"}, 
  {id:9, name:"Tamyres"}, 
  {id:11, name:"Abellll"}];

const filterArrayObjectForArray = names.map(names => names.name);
 
render();

const changeAmountOfElementsInPage = (valueSelect) => {
  elementsPerPage = valueSelect.value;
  pageCurrent = 0;
  render();
}

const next = () => {
  const namesFiltered = filterArrayObjectForArray.filter(filterName);
  if ((pageCurrent + 1) * elementsPerPage < namesFiltered.length) {
    pageCurrent++;
     render();
  }
}

const previous = () => {
  if ((pageCurrent - 1) * elementsPerPage >= 0)
    pageCurrent--;
  render()
}

function render() {

  const renderElements =  (text, position)=>{
      
      const placeOfElements = document.getElementById("resultado");
      const elementUl = document.createElement('UL');
      const elementButton = document.createElement('BUTTON');
      const textButton = document.createTextNode('Delete');
      const elementsPerPageUl = document.createTextNode(text+' ');
      
      elementButton.className='btn btn-danger btn-xs'
      elementButton.appendChild(textButton);
    
      elementUl.appendChild(elementsPerPageUl);
      elementUl.appendChild(elementButton);
      placeOfElements.appendChild(elementUl);
    
      elementButton.onclick = function(element) {
        placeOfElements.removeChild(elementUl);
  }
 
    
      
}
  
  const filterPositionOfElement = (_, position, arr) => {
    const isBiggerThanZero = position >= 0;
    const isGteStart = position >= pageCurrent * elementsPerPage;
    const isLtFinish = position < (pageCurrent + 1) * elementsPerPage;
    const isLtArrLength = position < arr.length;

    return isGteStart && isLtFinish && isLtArrLength && isBiggerThanZero
  }
  
  const filteredNames = filterArrayObjectForArray.filter(filterName);
  document.getElementById("resultado").innerHTML = '';

  filteredNames.filter(filterPositionOfElement).forEach(renderElements)
}

function filterName(str) {
  const wordForFilter = document.getElementById('valorInput').value;
  if (str.indexOf(wordForFilter) !== -1) {
    return str;
  }
}

function find() {
  pageCurrent = 0;
    render();
}
<head>
  <link rel="stylesheet" type="text/css" href="project.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<div id='programa1'> 
 <img id='icon-search' src='https://cdn2.iconfinder.com/data/icons/picons-essentials/57/search-128.png' width=20px> <input id='valorInput' />
  
    <button type="button" class="btn btn-dark " id="buscar" onClick='find()'>Search</button>
   <div id='buttons'>
        <button type="button" class="btn btn-primary" id='proximo' onClick="previous()"> Previous </button>
  
  <button type="button" class="btn btn-primary" ID='anterior' onClick="next()">Next</button>
  </div>
  
   <div id="resultado"> Carregando... </div>
    
  Deseja ver quantos elementos por vez:
  <select id='select' onchange="changeAmountOfElementsInPage(this)">
  <option value="3" >3</option>
  <option value="5" >5</option>
  <option value="10" >10</option>
</select>
  <h3 id='obs'> </h3>
</div>
  </div>
<script type="text/javascript" src="project.js"> </script>

The commented line was what I tried to do by putting a removeChild but did not give the expected result, because when it gives next and then previous he comes back.

2 answers

0

Each time a name is deleted, the show();

var ul = document.querySelector(".root");
var max = 2; //limite de pessoas a ser inserida no HTML

var names = [
"Marcelo",
"Fulanin",
"Jubisclaudia",
"Astolfina"
];



function remove(name) {
  let index = names.indexOf(name);
  if (index == -1) { return; }
  names.splice(index, 1);
  show();
}

function show() {
  ul.innerHTML = '';
  var count = 0;
  console.log(names);
  names.map(function(name){
    if (count >= max) { return; }
    let li = document.createElement("li");
    li.textContent = name;
    ul.appendChild(li);
    count++;
  })
  count = 0;
}

show();
<ul class="root">

</ul>

<button onclick="remove('Marcelo')">Remove</button>

Compatibility Array.prototype.map()

inserir a descrição da imagem aqui

0

You can use the method splice() within the function that removes the line, removing the item from the array by person’s name (will be removed all with equal names, if any).

To catch only the person’s name, used a replace with a regex to delete the button tag delete, I mean, I just want to get the text inside the ul.

Important to note that the ul that is creating does not possess li, what is wrong. A ul must possess a li: <ul><li> elementos </li></ul>

By picking up the name on ul, just make a forEach in the array and remove the entries that have the name captured. See:

let pageCurrent = 0;
let elementsPerPage = 3;
let novoArray = [];
const observation = document.getElementById('obs');

const names = [
  {id:0, name:"Jean"}, 
  {id:2, name:"Ricardo"}, 
  {id:9, name:"Tamyres"}, 
  {id:11, name:"Abellll"}];

const filterArrayObjectForArray = names.map(names => names.name);
 
render();

const changeAmountOfElementsInPage = (valueSelect) => {
  elementsPerPage = valueSelect.value;
  pageCurrent = 0;
  render();
}

const next = () => {
  const namesFiltered = filterArrayObjectForArray.filter(filterName);
  if ((pageCurrent + 1) * elementsPerPage < namesFiltered.length) {
    pageCurrent++;
     render();
  }
}

const previous = () => {
  if ((pageCurrent - 1) * elementsPerPage >= 0)
    pageCurrent--;
  render()
}

function render() {

  const renderElements =  (text, position)=>{
      
      const placeOfElements = document.getElementById("resultado");
      const elementUl = document.createElement('UL');
      const elementButton = document.createElement('BUTTON');
      const textButton = document.createTextNode('Delete');
      const elementsPerPageUl = document.createTextNode(text+' ');
      
      elementButton.className='btn btn-danger btn-xs'
      elementButton.appendChild(textButton);
    
      elementUl.appendChild(elementsPerPageUl);
      elementUl.appendChild(elementButton);
      placeOfElements.appendChild(elementUl);
    
      elementButton.onclick = function(element) {

         // linhas adicionadas
         const nomeRemover = elementUl.innerHTML.replace(/\s<[^>]*>[\w]+<[^>]*>/g, "");

         names.forEach(function(e,v){
            if(e.name == nomeRemover){
               names.splice(v,1);
            }
         });
         
         console.log(names);
         // linhas adicionadas

        placeOfElements.removeChild(elementUl);
  }
 
    
      
}
  
  const filterPositionOfElement = (_, position, arr) => {
    const isBiggerThanZero = position >= 0;
    const isGteStart = position >= pageCurrent * elementsPerPage;
    const isLtFinish = position < (pageCurrent + 1) * elementsPerPage;
    const isLtArrLength = position < arr.length;

    return isGteStart && isLtFinish && isLtArrLength && isBiggerThanZero
  }
  
  const filteredNames = filterArrayObjectForArray.filter(filterName);
  document.getElementById("resultado").innerHTML = '';

  filteredNames.filter(filterPositionOfElement).forEach(renderElements)
}

function filterName(str) {
  const wordForFilter = document.getElementById('valorInput').value;
  if (str.indexOf(wordForFilter) !== -1) {
    return str;
  }
}

function find() {
  pageCurrent = 0;
    render();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<div id='programa1'> 
 <img id='icon-search' src='https://cdn2.iconfinder.com/data/icons/picons-essentials/57/search-128.png' width=20px> <input id='valorInput' />
  
    <button type="button" class="btn btn-dark " id="buscar" onClick='find()'>Search</button>
   <div id='buttons'>
        <button type="button" class="btn btn-primary" id='proximo' onClick="previous()"> Previous </button>
  
  <button type="button" class="btn btn-primary" ID='anterior' onClick="next()">Next</button>
  </div>
  
   <div id="resultado"> Carregando... </div>
    
  Deseja ver quantos elementos por vez:
  <select id='select' onchange="changeAmountOfElementsInPage(this)">
  <option value="3" >3</option>
  <option value="5" >5</option>
  <option value="10" >10</option>
</select>
  <h3 id='obs'> </h3>
</div>
  </div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.