Insert onclick event into dynamically created input

Asked

Viewed 421 times

2

I have a table where the user can insert a row into the table and then delete it if necessary. For this, when it adds a Row, in the second cell I insert two cells. One contains the content and the other a button created dynamically. My problem is on this button. When I enter 1 line, it deletes correctly. But if I insert more than one line, it always deletes the last one that was inserted. It seems that the onclick event always keeps the parameters of the last line inserted. The code that creates this input and add the event:

        function inclui_item_extra(itemExtra, origem){
            var tabela      = '';
            var prod        = '';
            var idInput     = '';
            var idItemExtra = 0;
            switch(origem){
                case 'p1'   :
                    tabela  = 'tab_item_extra1';
                    idInput = 'produto';
                    prod = document.getElementById(idInput).value;
                    break;
                case 'p2'   :
                    tabela = 'tab_item_extra2';
                    idInput = 'produto2';
                    prod = document.getElementById(idInput).value;
                    break;
                case 'p3'   :
                    tabela = 'tab_item_extra3';
                    idInput = 'produto3';
                    prod = document.getElementById(idInput).value;
                    break;
                case 'p4'   :
                    tabela = 'tab_item_extra4';
                    idInput = 'produto4';
                    prod = document.getElementById(idInput).value;
                    break;
                default     :
            }
            prod = prod.split("|");
            if(prod.length == 2){
                var itemExtra   = itemExtra.split("|");


                id = gera_id(itemExtra[0].replace(' ', ''));
                var table       = document.getElementById(tabela);
                var row         = table.insertRow(0);
                row.id          = id;
                var cell1       = row.insertCell(0);
                var cell2       = row.insertCell(1);
                cell1.innerHTML = itemExtra[1];

                var deletaExtra = document.createElement("INPUT");
                deletaExtra.setAttribute("type", "button");
                deletaExtra.onclick = function (){
                    deletaItemExtra(id, tabela);
                }
            /*  
                deletaExtra.addEventListener("click", function(){
                    deletaItemExtra(id, tabela);
                });
            */
                deletaExtra.setAttribute("value", 'X');
                cell2.appendChild(deletaExtra);

            }else{
                document.getElementById(origem).value = '';
                document.getElementById(idInput).focus;
                alert("Produto não informado.");
            }
        }

        function deletaItemExtra(item, tabela){
            var x = document.getElementById(item);
            var id = x.id;
            //x.deleteRow(0);
            //x.parentElement.removeChild(x);
                var tab = document.getElementById(tabela);
                var linhas = tab.rows;
                var conta = 0;
                while(linhas[conta]){
                    if(id == linhas[conta].id){
                        alert(linhas[conta].id +" -- achei e vou deletar");
                        document.getElementById(tabela).deleteRow(conta);
                    }
                    conta++;
                }
        /*
                var z = document.getElementById(tabela).rows.length;
                var y = 0;
                for(y =z-1; y >= 0; y--){
                    alert('-'+ document.getElementBy.row(y).id);
                    if(item == x.row(y).id){
                        document.getElementById(tabela).deleteRow(y);
                    }

                }
        */
            if(document.getElementById(item) != null){
                alert('Ainda é encontrado no sistema'); 
            }else{
                alert('Foi totalmente deletado do sistema'); 
            }
        }

I tried to add the event directly in onclick and also with the addEventeListener function but the two have the same result. I have a function that doesn’t let duplicate ids exist. Follow code:

function gera_id(ie) {
  var idExiste = false;
  var id = 0;
  while (idExiste == false) {
    id = "ie" + Math.floor((Math.random() * 10000) + 1) + '_' + ie;

    if (document.getElementById(id) == null) {
      idExiste = true;
    }
  }
  return id;
}
  • This happens because you are dynamically creating the buttons but using the same id for them, so only the last id created will work, you use Jquery? This can be solved in a very simple way with him.

  • It is interesting you add it to the question. Remember: The more detailed the question the faster you get an answer.

  • Sorry. Could you show me how to do in jquery? or any other suggestion about what the problem is?

  • Matheus, where are you calling the function to randomize the id? also show the function deletaItemExtra(id, tabela);

  • I added the functions to the question.

No answers

Browser other questions tagged

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