0

I have the following dynamic code:

var data = [
   {codigo: "1", Utente: "Teste", },
   {codigo: "2", Utente: "Teste1", },
   {codigo: "3", Utente: "Teste2",},
   {codigo: "4", Utente: "Teste3", },
   {codigo: "5", Utente: "Teste4", },
   {codigo: "6", Utente: "Teste5", },
];

$(document).on('click', '.dad-inf', function(){

var linha = ``;

for (var i = 0; i < data.length; i++) {
codigo = data[i].codigo;
Utente = data[i].Utente;

linha += `<div class="col-md-6 col-xl-3">
            <a href="#" class="dropdown-item btn btn-warning histor-uten">
              <div class="profile-photo-div" id="profile-photo-div">
                <div class="profile-buttons-div">
                  <div class="profile-img-input" id="profile-img-input">
                    <label class="butttton" id="change-photo-label" for="change-photo">#${Utente}</label>
                    <input type="hidden" name="id_utt" value="${codigo}">
                  </div>
                </div>
               </div>
              </a>
            </div>`;
   }
                  
   $(".tesssste").html(linha);
 
});

$(document).on('click', '.histor-uten', function(){

  var id_utt = $("input[name='id_utt']").val();
  console.log(id_utt);

});

$(function() {
    $(".btn-show").click(function(e) {
      e.preventDefault();
      el = $(this).data('element');
      $(el).show();
      $("section > div").not(el).hide();
    });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>

<a href="s105" data-element="#minhaDiv105" class="btn-show dad-inf">Utentes</a>

<section id="s105">
  <div id="minhaDiv105">
    <div class="row tesssste">
    </div>
  </div>
</section>

This code generates a div with several users and their respective user code. so far so good.

The problem I'm having comes after this step. After returning the users, when I click for example on the user with the user code number 3, it returns the user code 1.

And the correct one, if I click on the user with the code number 3, it should return the user code number 3 and not the 1.

Can you help?

Bruno
  • 801
  • 5
  • 11
  • Why are you using `Object.keys` with an array? – evolutionxbox Sep 20 '22 at 08:53
  • @evolutionxbox I will change and use for, because in my code I use for. and I use the for because it has to loop, to generate the various users – Bruno Sep 20 '22 at 08:55
  • Does this answer your question? [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – icecub Sep 20 '22 at 09:01
  • @icecub I didn't quite understand the example you posted and I couldn't apply it to my code. Can you help with an example? – Bruno Sep 20 '22 at 09:07
  • You are creating dynamic content. So you need to use event delegation to properly attach a click event handler to each user. In simple words: An event handler that responds to all clicks no matter what initiates it. Then checks if the click was fired by a dynamic button and if so, gets its attributes / contents. So if a click takes place anywhere on the website, the event handler "asks" if a button was clicked. If not, it'll just do nothing. If it is, it checks which button was clicked and returns the information linked to that button. – icecub Sep 20 '22 at 09:15
  • I can work on an example for you, but I hope you don't mind if I write it in pure javascript and not jQuery? – icecub Sep 20 '22 at 09:21
  • @icecub No problem, you can write in jquery or pure javascript – Bruno Sep 20 '22 at 09:23
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248193/discussion-between-junior-and-icecub). – Bruno Sep 20 '22 at 09:47

2 Answers2

1

Here is an example using Event Delegation. You basically check which button it being clicked and get the child input element of its parent instead of the first one available in the document.

var data = [
   {codigo: "1", Utente: "Teste", },
   {codigo: "2", Utente: "Teste1", },
   {codigo: "3", Utente: "Teste2",},
   {codigo: "4", Utente: "Teste3", },
   {codigo: "5", Utente: "Teste4", },
   {codigo: "6", Utente: "Teste5", },
];

$(document).on('click', '.dad-inf', function(){

var linha = ``;

for (var i = 0; i < data.length; i++) {
codigo = data[i].codigo;
Utente = data[i].Utente;

linha += `<div class="col-md-6 col-xl-3">
            <a href="#" class="dropdown-item btn btn-warning histor-uten">
              <div class="profile-photo-div" id="profile-photo-div">
                <div class="profile-buttons-div">
                  <div class="profile-img-input" id="profile-img-input">
                    <label class="butttton" id="change-photo-label" for="change-photo">#${Utente}</label>
                    <input type="hidden" name="id_utt" value="${codigo}">
                  </div>
                </div>
               </div>
              </a>
            </div>`;
   }
                  
   $(".tesssste").html(linha);
 
});

$(document).on('click', '.histor-uten', function(e){
    let parent = $(this);
    // First make sure it selects the element with the histor-uten class
  if(!parent.hasClass('histor-uten')){
    parent = $(this).closest('.histor-uten');
  }

    // Get the child input from the parent instead of the first one in the document
  var id_utt = $(parent.find("input[name='id_utt']")).val();
  console.log(id_utt);

});

$(function() {
    $(".btn-show").click(function(e) {
      e.preventDefault();
      el = $(this).data('element');
      $(el).show();
      $("section > div").not(el).hide();
    });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>

<a href="s105" data-element="#minhaDiv105" class="btn-show dad-inf">Utentes</a>

<section id="s105">
  <div id="minhaDiv105">
    <div class="row tesssste">
    </div>
  </div>
</section>
icecub
  • 8,615
  • 6
  • 41
  • 70
0

You have to access input inside event.target, something like this:

var data = [
   {codigo: "1", Utente: "Teste", },
   {codigo: "2", Utente: "Teste1", },
   {codigo: "3", Utente: "Teste2",},
   {codigo: "4", Utente: "Teste3", },
   {codigo: "5", Utente: "Teste4", },
   {codigo: "6", Utente: "Teste5", },
];

$(document).on('click', '.dad-inf', function(){

var linha = ``;

for (var i = 0; i < data.length; i++) {
codigo = data[i].codigo;
Utente = data[i].Utente;

linha += `<div class="col-md-6 col-xl-3">
            <a href="#" class="dropdown-item btn btn-warning histor-uten">
              <div class="profile-photo-div" id="profile-photo-div">
                <div class="profile-buttons-div">
                  <div class="profile-img-input" id="profile-img-input">
                    <label class="butttton" id="change-photo-label" for="change-photo">#${Utente}</label>
                    <input type="hidden" name="id_utt" value="${codigo}">
                  </div>
                </div>
               </div>
              </a>
            </div>`;
   }
                  
   $(".tesssste").html(linha);
 
});

$(document).on('click', '.histor-uten', function(event){
  var id_utt = $(event.target).find("input[name='id_utt']")[0].value;
  console.log(id_utt);

});

$(function() {
    $(".btn-show").click(function(e) {
      e.preventDefault();
      el = $(this).data('element');
      $(el).show();
      $("section > div").not(el).hide();
    });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>

<a href="s105" data-element="#minhaDiv105" class="btn-show dad-inf">Utentes</a>

<section id="s105">
  <div id="minhaDiv105">
    <div class="row tesssste">
    </div>
  </div>
</section>
Irakli Tchedia
  • 267
  • 1
  • 7
  • This code only has the problem that when I run your example it returns this error `"Uncaught TypeError: Cannot read properties of undefined (reading 'value')"`. Can you help solve? – Bruno Sep 20 '22 at 09:41
  • @Junior it might happen if there is no input element with `name='id_utt'` under the element you are clicking – Irakli Tchedia Sep 20 '22 at 10:10
  • @Iraque Tchedia But there is always an input element, so I find it strange. But I solved with the other answer – Bruno Sep 20 '22 at 11:04