2

I've got several buttons that look like:

<span class="input-group-btn">
  <a class="btn btn-default" href="#">
    <i class="fa fa-barcode"></i> Scan
  </a>
</span>

But I need to be able to detect which of the x number of buttons has been pressed. Is there any way I can do that with JQuery/JavaScript?

The buttons are created dynamically like:

$('input[role="barcode"]').before('<span class="input-group-btn"><a class="btn btn-default" href="#"><i class="fa fa-barcode"></i> Scan</a></span>')

As an alternative is it possible to give each button a different id or href to differentiate between them on creation?

4
  • you can create an counter and add it to your elemnts id attribute Commented Oct 6, 2015 at 18:48
  • You need delegate 'click' event to parent container of buttons. Second you need mark each button by index, you can use #id, .class, data-property. And listen on container target of event click Commented Oct 6, 2015 at 18:51
  • api.jquery.com/on Commented Oct 6, 2015 at 18:51
  • 1
    These are not buttons. This is a button: <button>...</button> Commented Oct 6, 2015 at 18:52

4 Answers 4

2

try $.index();

$('.btn-default').click(function(){
    var index = $(this).parent().index();
    alert(index);
});

https://jsfiddle.net/7daffjh8/18/

Sign up to request clarification or add additional context in comments.

Comments

0
$('input[role="barcode"]').each( function(index, elem) {
  $(this).before(
     '<span class="input-group-btn">'
    +  '<a class="btn btn-default" href="#" data-index="' + index + '">'
    +    '<i class="fa fa-barcode"></i> Scan'
    +  '</a>'
    + '</span>'
  );
});

$(document).on('click', 'a.btn', function () {
  console.log('You clicked on link with index', this.getAttribute("data-index"));
});

Comments

0

You can use the other described JQUERY methods OR

You can yourself give a manual number to button while creating like

<span class="input-group-btn">
  <a class="btn btn-default" index="1" href="#">
    <i class="fa fa-barcode"></i> Scan
  </a>
</span>

OR Using JS like

for(i=0 to n){
  var l_button = document.createElement("Button");
  l_button.setAttribute("index",i);
}

And when you want to retrieve the index you can do like:

var target = event.target || event.srcElement;
var index_val = target.getAttribute("index");

Comments

0

You can detect which button was clicked in the event handler:

$('.input-group-btn').click(function(e){
    var index = $(e.target).index();
    console.log(index);
});

1 Comment

e.target returns a dom node not a jQuery object. See api.jquery.com/event.target

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.