-1

EDIT: SOLVED. Thanks everyone!

I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!

$(document).ready(function() {
  var anchors = document.getElementsByClassName('editButton');
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
      $.ajax({
        method: "GET",
        url: "/testedit.php",
      }).done(function(data) {
        var id = anchor.value;

        /* from result create a string of data and append to the div */

        var result = data;
        var string = '<p>ID is ' + id + '</p><br>';

        $("#records").html(string);
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div>
  • I moved your code into a code snippet. Could you add the necessary HTML to reproduce your problem? – Daan May 29 '20 at 06:42
  • My buttons get generated automatically, and each is associated with an element in a database. I added the code for the buttons, but I don't think anything else is really relevant. – Saba Kvesitadze May 29 '20 at 06:50
  • You could copy and paste the generated code (client side) so that we could better understand your problem. – Daan May 29 '20 at 07:08

6 Answers6

1

Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.

So your final code should be something like this:

$(document).ready(function() {
  $('.editButton').click(function() {
  console.log('innerHTML is:', $(this).html())
  console.log('id is:', $(this).attr('id'))
    $.ajax({
      method: "GET",
      url: "/testedit.php",
    }).done(function(data) {
      var id = $(this).value;

      /* from result create a string of data and append to the div */

      var result = data;
      var string = '<p>ID is ' + id + '</p><br>';

      $("#records").html(string);
    });
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
  <button class="editButton" id="firstButton">button 1</button>
  <button class="editButton" id="secondButton">button 2</button>
  <button class="editButton" id="thirdButton">button 3</button>
  <button class="editButton" id="fourthButton">button 4</button>
</div>
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
0

You can use getAttribute. Like:

var anchors = document.getElementsByClassName('editButton');

// Id of anchors
id_of_anchor = anchors.getAttribute("id");

Refs

EDIT

anchor.onclick = function() {
    id_of_anchor = $(this).attr("id");
});
Community
  • 1
  • 1
Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30
0

You have jQuery in your application, there is easier and more readable way to do it with jQuery;

$(document).ready(function() {
    $(".editButton").each(function(a, b) {
        $('#' + $(b).attr('id')).on('click', function() {
            $.ajax({
                method: "GET",
                url: "/testedit.php",
            }).done(function(data) {
                var id = $(b).attr('id');

                /* from result create a string of data and append to the div */

                var result = data;
                var string = '<p>ID is ' + id + '</p><br>';

                $("#records").html(string);
            });
        });
    });
});

Example: https://jsfiddle.net/wao5kbLn/

Cem
  • 176
  • 8
  • Tried it, doesn't work, sorry. Also, I noticed you have two parameters in the .each function a and b, but a doesn't get used anywhere, so why is it needed? – Saba Kvesitadze May 29 '20 at 06:49
  • Just check the fiddle you will see that it is working, it is not working in your case probably you dont have $(b).val() if you want to get text you should write $(b).text(), a => index, b=> item I used b, I dont need a. – Cem May 29 '20 at 06:52
  • @SabaKvesitadze I fixed it for you, now click event will give you to id of the item. – Cem May 29 '20 at 06:58
0

You need to look in to JavaScript closures and how they work to solve this. When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.

One simple way to resolve this issue is listed below.

<div id="records"></div>

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>


<script type="text/javascript"> 
  $(document).ready(function(){ 
    var anchors = document.getElementsByClassName('editButton');
    for(var i = 0; i < anchors.length; i++) {           

            //Wrap the function with an IIFE and send i value to the event listener

            (function(anchor){

             anchor.onclick = function() {
               $.ajax({ 
                  method: "GET", 
                  url: "/testedit.php",
               }).done(function( data ) { 
                  var id = anchor.value;

                  /* from result create a string of data and append to the div */

                  var result= data; 
                  var string='<p>ID is '+id+'</p><br>';

                  $("#records").html(string); 
              });
            }

           })(anchors[i]); 

        }
    }
}); 

You can read more about this in JavaScript closure inside loops – simple practical example

Thusitha
  • 3,393
  • 3
  • 21
  • 33
0

save the button with button = this when run the onclick function and use it

 $(document).ready(function(){ 
 var anchors = document.getElementsByClassName('editButton');
   for(var i = 0; i < anchors.length; i++) {
     var button;
     var anchor = anchors[i];
     anchor.onclick = function() {
       button = this;
       $.ajax({ 
         method: "GET", 
         url: "/testedit.php",
       }).done(function( data ) {                   


         /* from result create a string of data and append to the div */

         var result= data; 
         var string='<p>ID is '+ button.value +'</p><br>';

         $("#records").html(string); 
       }); 
     }
   }
}); 

https://jsfiddle.net/x02srmg6/

user3401335
  • 2,335
  • 2
  • 19
  • 32
0

In your code..

 var id = anchor.value;

could be

 var id = anchor.id;

but I recommend you to use event delegation

If you have a html like this

<div id="buttonArea">
  <a class="editButton" id="1"/>
  <a class="editButton" id="2"/>
  <a class="editButton" id="3"/>
  .......(so many buttons)
</div>

you can code like below.

$(document).ready(function(){ 
  $('#buttonArea').on('click', 'a.editButton', function (event) {
    var anchor = event.currentTarget;
    $.ajax({ 
      method: "GET", 
      url: "/testedit.php",
    })
    .done(function(data) { 
      var id = anchor.id;

      /* from result create a string of data and append to the div */

      var result= data; 
      var string='<p>ID is '+id+'</p><br>';

      $("#records").html(string); 
    });
}
FirePizza
  • 31
  • 2