Assign function to dynamically generated button

Asked

Viewed 632 times

0

Personal my problem is a little difficult for me to explain. I have these buttons which are added each time when it is clicked on the "+" and when it clicks on any of these button they remove the div father (.list-group-item).

The point is that I can only assign this function to these buttons directly in the html element (onclick="removeField("+amntFileds+")") but I wanted something like:

document.querySelector(".remove-button").onclick=function(){...}

Unfortunately I can’t do this because the buttons are added dynamically, and before adding them, they still don’t exist by returning the selector error that doesn’t find it. I’m trying to use this code in an extension to the Chrome, and cannot use inline code...

Refused to execute inline Event Handler because it violates the following Content Security Policy Directive: "script-src 'self' blob: filesystem: Chrome-Extension-Resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline Execution.

JS:

var amntFileds = 1;
var superObj = document.querySelector(".list-group");
var btnAdd = document.querySelector(".add-button");

btnAdd.onclick = function(){
   Element.prototype.setAttributes = function(attrs){
      for (var index in attrs){
         if ((index == 'styles' || index == 'style') && typeof attrs[index] == 'object'){
            for (var prop in attrs[index]){
               this.style[prop] = attrs[index][prop];
            }
         }else if (index == 'html'){
            this.innerHTML = attrs[index]
         }else{
            this.setAttribute(index, attrs[index]);
         }
      }
   };

   //Criando o elementos;
   var subObj = document.createElement("a");
   var inputRemove = document.createElement("button");

   //----------------Setando atributos dinamicamente-----------------\\
   //Definindo atributos ao subObj(div list-group-item):
   subObj.setAttributes({
      "id" : "sub-field"+amntFileds,
      "class" : "list-group-item"
   });

   //Definindo atributos ao inputRemove(Botão de exclusão de comandos)
   inputRemove.setAttributes({
      "type" : "button",
      "class" : "remove-button",
      "html" : "✘",
      //"onclick" : "removeField("+amntFileds+")"
   });
   //-----------------------------------------------------------------\\

   //Inserindo o elementos no subObj(list-group-item):
   subObj.appendChild(inputRemove);
   superObj.appendChild(subObj);
   amntFileds++;
}

function removeField(id){

   //Recebendo id de campo clicado
   var subObj = document.querySelector("#sub-field"+id); 

   //Removendo o DIV com id específico do nó-pai:
   var removed = superObj.removeChild(subObj);        

   //Decrementando campo adicionado em 1;
   amntFileds--;
   console.log("Campo "+amntFileds+" removido!");
}

HTML:

<div class="list-group">
</div>
<br><button type="button" class="add-button">&#10010;</button><br>
<script type="text/javascript" src="action.js"></script>
  • Because you’d like it that way if onclick works?

  • it is not recommended not to use inline function?

  • I understand your question.

  • There is no problem in using onclick.. your code is working perfectly... want to use querySelector would complicate.

  • Tip: leave the onclick even, it is even better, in my opinion... delete your question because it will not be useful any resolution beyond that

  • I am trying to use this code in an extension for chorme, and it seems that you cannot use inline code... Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

  • You said "it seems"... if it works, ignore these warnings... from what I’ve seen, it doesn’t seem to be about the onclick

  • but it doesn’t work

  • Then you’d better put those details in the question.... otherwise people will waste time trying to solve something that works normally in the browser.

  • Your question is somewhat confused and details are lacking. Assigning the click event by code does not affect the fact that the button is only added later. If it is only added later, only at the moment it is added is that you assign the click with addEventListener(). Not to mention create html with innerHTML is much easier, especially if you use string interpolation.

Show 5 more comments

1 answer

0

The easiest way to work with events in dynamically created elements is by using jQuery see:

$('body').on('click', '.uma-classe-qualquer', function(evt) {
    // aqui é possível pegar qualquer informação do elemento (id, data, etc...)
    alert($(this).attr('id'))
})

Already if the use of jQuery is not feasible in your project the way is to use addeventlistener in the elements you add dynamically example:

let inputRemove = document.createElement("button")
// adicione um "ouvinte"
inputRemove.addEventListener('click', function(evt) {
    // por exemplo para pegar o id:
    alert(this.id)
}, false)

Note that you can specify a function as a reference instead of declaring a:

// awesome function
function coolFunc(evt) {
    alert(this.id)
}
// handler
inputRemove.addEventListener('click', coolFunc, false)
  • The "downvoter" could suggest what is wrong in my answer, it would help to correct and find a solution to the issue #FIKADICA

Browser other questions tagged

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