When clicking on an item in a list, enter its text in input

0

I'm making a list of tasks in JS, where there is an input and a button that when you press, add the task together with two edit and delete buttons.

I have problems when editing, I would like to click on the edit icon, take the text of the task and input it in the input and then when the Edit button is replaced in the same place from the list where he was.

The list goes like this:

                <ul class="list-group" id="lista">
                <li class="list-group-item">
                    <a class="float-left" href="#"><span class="badge badge-secondary mr-2">05/07/2018</span>Estudiar</a>
                    <button class="btn btn-sm btn-danger btn-borrar float-right"><i class="fas fa-trash-alt"></i></button>
                    <button class="btn btn-sm btn-warning float-right mr-2" onclick="editarTarea(this);"><i class="fas fa-pencil-alt"></i></button>
                </li>
                <li class="list-group-item">
                    <a class="float-left" href="#"><span class="badge badge-secondary mr-2">10/04/2018</span>Terminar códigos...</a>
                    <button class="btn btn-sm btn-danger btn-borrar float-right"><i class="fas fa-trash-alt"></i></button>
                    <button class="btn btn-sm btn-warning float-right mr-2" onclick="editarTarea(this);"><i class="fas fa-pencil-alt"></i></button>
                </li>
                <li class="list-group-item">
                    <a class="float-left" href="#">
                        <span class="badge badge-secondary mr-2">15/07/2018</span>
                        Continuar con freeCodeCamp
                    </a>
                    <button class="btn btn-sm btn-danger btn-borrar float-right"><i class="fas fa-trash-alt"></i></button>
                    <button class="btn btn-sm btn-warning float-right mr-2" onclick="editarTarea(this);"><i class="fas fa-pencil-alt"></i></button>
                </li>

That is, what I want to happen when I click the EDIT button, is to take the name of the task (Study or Finish Codes or Continue with freeCodeCamp, depending on which one you click).

and the function in JS:

function editarTarea(){
btnAgregar.innerText = 'Editar Tarea';
document.getElementById('tareaInput').value = 'Aqui no se como llamar al nombre de la tarea;
}

I hope you can give me a hand. I leave the codepen so they understand better: link

Thank you!

    
asked by ZeR0ByTe 15.07.2018 в 20:20
source

2 answers

1

As you have already been told in the comments, it is best to create an id for the task, so that the code can identify it, reviewing your code and add some modifications that may be (I already tried and it works):

Let's go first with the add task function

function agregarTarea(){
let fecha = document.createTextNode(hoyFecha());

//Creas un nuevo span para tarea, asi podras deliminar el texto y usar la fecha unix para identificar cada elemento
let spanTarea = document.createElement('span');
let fechaUnix = Date.now();
    ////


let nombreTarea = document.getElementById('tareaInput').value;
let nuevoElemento = document.createElement('li');
let enlace = document.createElement('a');
let spanFecha = document.createElement('span');
let botonEditar = document.createElement('button');
let botonBorrar = document.createElement('button');
let iconoEditar = document.createElement('i');
let iconoBorrar = document.createElement('i');
let nuevaTarea = document.createTextNode(nombreTarea);

//Validación si está vacio, agrega la clase is-Valid + mensajeError.
if (nombreTarea === '') {
    document.getElementById('tareaInput').className = 'form-control mb-2 is-invalid';
    let mensajeError = document.getElementById('mensajeError');
    mensajeError.className = 'form-text text-danger mb-2';
}
else{
    // Sino, quita la clase is-invalid y mensajeError  y agrega la nueva tarea.
    document.getElementById('tareaInput').className = 'form-control mb-2';
    mensajeError.className = 'form-text text-danger mb-2 d-none';

    //A partir de aqui empieza a CREAR todo el HTML de la TAREA que se agregará.
    nuevoElemento.className = 'list-group-item';
    //Le indico los atributos al enlace
    enlace.setAttribute('href', '#');
    //Le indico la clase al enlace
    enlace.className = 'float-left';

    enlace.appendChild(spanFecha);

    spanFecha.className = 'badge badge-secondary mr-2';

    spanFecha.appendChild(fecha);
    //Agrego el texto/nombre de la tarea al enlace


    //*******************Agregas el Span, y le agregas un atributo ID que corresponda con la fecha unix, para que no haya Ids repetivos
    enlace.appendChild(spanTarea);
    spanTarea.setAttribute('id', fechaUnix);
    spanTarea.appendChild(nuevaTarea);



    //Agrego el enlace al LI
    nuevoElemento.appendChild(enlace);

    // ############ SE CREA EL BOTON BORRAR ##########

    nuevoElemento.appendChild(botonBorrar);

    botonBorrar.className = 'btn btn-sm btn-danger btn-borrar float-right'

    botonBorrar.appendChild(iconoBorrar);

    iconoBorrar.className = 'fas fa-trash-alt';

    // ############ FIN BOTON EDITAR ##########

    // ############ SE CREA EL BOTON EDITAR ##########

    nuevoElemento.appendChild(botonEditar);

    botonEditar.className = 'btn btn-sm btn-warning float-right mr-2'

    botonEditar.appendChild(iconoEditar);


    //*******************En vez de pasar el elemento this, pasas el id del span

    botonEditar.setAttribute('onclick', 'editarTarea('+ fechaUnix +');');

    iconoEditar.className = 'fas fa-pencil-alt';

    // ############ FIN BOTON EDITAR ##########

    //Agrego la nueva tarea a la lista
    lista.appendChild(nuevoElemento);
    //Al ingresar la tarea, deja el contenido del input vacio.
    document.getElementById('tareaInput').value = '';
}

actualizarTarea();

}

In the Edit task function, adapt it as follows

function editarTarea(id){
    btnAgregar.innerText = 'Editar Tarea';
    //Tomas el conteido de la etiqueta span que es el nombre de la tarea
    document.getElementById('tareaInput').value = 
    document.getElementById(id).innerHTML;
}

That should be enough for the button to add the text to the input. I hope it serves you.

Respect, to have the edition saved in the same position, I propose the following:

    //Agrega el evento click a TODOS los elementos de la lista para TACHAR Y ELIMINAR la tarea.
   //Se hace al principio y despues de agregar una tarea.
       function actualizarTarea(){
       for (let i = 0; i < listaTareas.children.length; i++) {
           //Le asigna la funcion tacharTarea a cada elemento de la lista.
           //COMENTAS LA LINEA DE ABAJO, YA NO ES NECESARIA******************
           //listaTareas.children[i].addEventListener('click', tacharTarea);
           //Le asigna la funcion eliminarTarea a cada elemento de la lista.
           btnBorrar[i].addEventListener('click', eliminarTarea);
       }
   }


//Esta variable se crea para propagar el id del item en edicion cuando se aplica en addEventListener
//con la funcion aplicarCambiosTarea. Aunque podria evitarse el uso de esta variable usando
//una funcion anonima en addEventListener, esto luego dificultaria usar removeEventListener
var idEnEdicion = 0;

function editarTarea(id){
    btnAgregar.innerText = 'Editar Tarea';
        //Tomas el conteido de la etiqueta span que es el nombre de la tarea
    document.getElementById('tareaInput').value = document.getElementById(id).innerHTML;

    idEnEdicion = id;//Se toma el id y se asigna a la variable para poder pasar el valor a updateTarea
    //Se remueve el evento agregar y se intercambia por editar, esto para separar cada tarea
    btnAgregar.removeEventListener('click', agregarTarea);
    btnAgregar.addEventListener('click', aplicarCambiosTarea);//Aplica los cambios realizados
}


//Se crea esta nueva funcion para aplicar los cambios provenientes de una edicion
function aplicarCambiosTarea(){
    //Toma el valor del input y lo actualiza en el item que se esta modificando
    document.getElementById(idEnEdicion).innerHTML = document.getElementById('tareaInput').value;

    //Finalizada la edicion, se restaura el boton a su estado inicial de agregar tarea
    btnAgregar.innerText = 'Agregar Tarea';

    btnAgregar.removeEventListener('click', aplicarCambiosTarea);

    btnAgregar.addEventListener('click', agregarTarea);
    document.getElementById('tareaInput').value = "";

}

That should be enough with that.

    
answered by 15.07.2018 / 23:27
source
0

You could get it without adding id, but the button to confirm an edition would be different from sending a new task, and if the list of tasks is empty by default it would be easier, so that in your case all the span elements are created with js. Your problem was the same as I had a while ago to create a comment system, I solved it by creating a new button to confirm the edition, I tried to leave only the essential thing to execute it here, I had tried to translate it to your example but to do it you would have to change several things that you have.

// VARIABLES:

var comentarios = document.getElementById("comentarios");
var boton = document.getElementById("boton");
var textarea = document.getElementById("textarea");
var edicion = false;

// FUNCION PARA AÑADIR NUEVOS COMENTARIOS

function anadir() {
    var div = document.createElement("div");
    comentarios.appendChild(div);
    var p = document.createElement("p");
    var hr = document.createElement("hr");
    var eliminar = document.createElement("input");
    var editar = document.createElement("input");
    p.innerHTML = textarea.value;
    p.setAttribute("class", "p");
    hr.setAttribute("class", "hr");
    eliminar.setAttribute("class", "eliminar");
    editar.setAttribute("class", "editar");
    div.appendChild(p);
    div.appendChild(eliminar);
    div.appendChild(editar);
    div.appendChild(hr);
    textarea.value = "";
    eliminar.type = "button";
    eliminar.value = "Eliminar";
    editar.type = "button";
    editar.value = "Editar";
    textarea.focus();

  // PARA ELIMINAR

  function eliminarc() {
    div.remove();
  }
  eliminar.addEventListener("click", eliminarc);

  // FUNCION PARA EDITAR UN COMENTARIO

  function editarc() {
   // Se crea un nuevo boton para confirmar la edicion y sera colocado en la posicion del boton de editar
    var botone = document.createElement("input");
    botone.type = "button";
    botone.value = "Confirmar edicion";
    div.replaceChild(botone, editar);
    botone.setAttribute("class", "botone");
    
    // El textarea coge el valor del p donde se pulse editar 
    textarea.value = p.innerText;
    p.innerHTML = "";
    textarea.focus();
    edicion = true;

    // FUNCION PARA CONFIRMA EDICION

    function edicionc() {
      p.innerHTML = textarea.value;
      div.replaceChild(editar, botone);
      textarea.value = "";
      textarea.focus();
      edicion = false;
    }
    botone.addEventListener("click", edicionc);
  }
  editar.addEventListener("click", editarc);
}
boton.addEventListener("click", anadir);
* {margin:0;padding:0;}
body {background:green;}
.comentarios {width:80%;background:#A9F5A9;;margin:auto;}
.comentarios > span {font-size:2em;font-weight:bold;}
.nombre {display:block;margin-left:5em;}
.nuevo {margin-top:1em;}
textarea {width:60%;height:10em;margin-left:5em;float:left;}
.boton {width:6em;height:1.5em;font-size:1em;margin-left:1em;margin-top:7em;margin-bottom:1em;}
.boton:hover {cursor:pointer;}
.p {margin-left:5em;margin-bottom:0.5em;margin-top:0.5em;clear:both;}
.pnom {margin-left:4.2em;margin-top:0.5em;}
.hr {color:black;width:90%;margin:auto;border:1px solid black;}
.eliminar {width:4.5em;height:2em;display:inline-block;margin-left:5em;margin-bottom:1em;}
.eliminar:hover {cursor:pointer;}
.editar {width:4em;height:2em;display:inline-block;margin-left:1em;margin-bottom:1em;}
.editar:hover {cursor:pointer;}
.botone {width:9em;height:2em;margin-left:1em;}
.botone:hover {cursor:pointer;}
<div id="comentarios" class="comentarios">
  <span>Comentarios.</span>
  <div id="nuevo" class="nuevo">
      <textarea id="textarea" placeholder="Deja un comentario"></textarea autofocus>
      <button id="boton" class="boton">Enviar</button>
  </div>
</div>

The complete example is here: link , and if you need help transferring it to your example, tell me about it and try to help you.

    
answered by 15.07.2018 в 23:43