1

I'm pretty new to web development (coming from an AV control system programming background) and am trying to do something that I'm convinced has to be super easy, but I'm coming up short. Basically I've created an array variable of buttons on a document, and need to determine which button was pressed. For example, let's say I have four buttons with ID's "id1" - "id4" Here's what I've got in JS:

$(document).ready(function(){
    var sourceBtns = [];
    var lastPressedIndex;

   for(i=1;i<=4;i++){
       sourceBtns.push(document.getElementById("id"+i));
   }

   for(i=1;i<=sourceBtns.length;i++){
       sourceBtns[i-1].addEventListener("click",lastPressed);
   }

    function lastPressed(){      
       //need to assign lastPressedIndex here
   }
});
  • 2
    `console.log(this)` – epascarello Nov 21 '17 at 17:04
  • 1
    using jquery if you have IDs like id1, id2,id3 then you can use jquery selector like this $("button[id^='id']").on('click', function(){console.log(this)}), this way you can get the last pressed button – Abid Nawaz Nov 21 '17 at 17:13
  • 1
    i don't think the duplicate this question was closed with is very relevant, this may be more useful: https://stackoverflow.com/questions/10291017/how-to-get-id-of-button-user-just-clicked – billyonecan Nov 21 '17 at 17:16

1 Answers1

2

Is this what you're looking for?

$(document).ready(function() {
  var sourceBtns = [];
  var lastPressedIndex;

  $("button[id^='id']").click(function() {
    lastPressedIndex = this.id;
    console.log(lastPressedIndex);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="id1">1</button>
<button type="button" id="id2">2</button>
<button type="button" id="id3">3</button>
<button type="button" id="id4">4</button>
emshore
  • 489
  • 6
  • 15
  • 1
    The code you have written is right but only using $('botton') will attach click event to others buttons too so here the ID's are incremental so we will use $("button[id^='id']") to avoid other buttons from click event fire – Abid Nawaz Nov 21 '17 at 17:21
  • @AbidNawaz This is an improvement, thanks for adding. I was illustrating the simplest solution first, which of course can always be extended. – emshore Nov 21 '17 at 17:23
  • 1
    `$(this).attr("id")` can be simply `this.id` – Taplar Nov 21 '17 at 17:32
  • @Taplar Thanks, updated code with your simplification. – emshore Nov 21 '17 at 17:35