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

0

I have a code that renders the Array elements on the screen, and each element of Array , has a delete button next to it.

I wanted to know how to delete it from Array and consequently remove it from the screen and instead of the element that was deleted 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 the one I tried to do, putting a removeChild but it did not give the expected result, because when it gives next and then previous it returns.

    
asked by anonymous 04.03.2018 / 18:57

2 answers

0

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

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()

    
04.03.2018 / 19:35
0

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

To get only the person name , I used a replace with a regex to delete the delete button tag, of ul .

  

It's important to note that the ul you are creating does not have li , which   it's wrong. A ul must have a li : <ul><li> elementos </li></ul>

When getting the name in 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><scriptsrc="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>
    
04.03.2018 / 19:44