Aaron
Aaron

Reputation: 4480

jQuery click one button end up clicking all button with same class

I have a foreach loop that populates my page. This populates several input tags that are buttons, all the buttons have the same class. When I click one button all the buttons are clicked. Is there a way so when I only click one button it only responds to that button. If I have twenty buttons and click a button I get 20 alert("test"). What do I change so I only get one alert("test").

Here is my HTML with some Laravel

<input class="interview-yes" id="{{$scan->id}}" type="submit" value="Yes"">

Here is my jquery

$('.interview-yes').click(function () {
  alert($(this.id));
)};

Upvotes: 2

Views: 984

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Check this method instead:

$(document).on('click','.interview-yes',function () {
  alert($(this).attr('id'));
)};

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12181

Since your button are dynamic you need to event delegate.

$(document).on('click', 'input.interview-yes', function () {
  console.log($(this).attr('id'));
)};

Here you go with an example

for(var i=0; i<10; i++){
  $('body').append(`<input class="interview-yes" id="input_${i}" type="submit" value="Yes" />`);
}

$(document).on('click', 'input.interview-yes', function(){
  console.log($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hope this will help you.

Upvotes: 1

Stentor
Stentor

Reputation: 84

Quick answer: The behavior you have is coherent with the code you have written: Install an event handler on each input of class "interview-yes", and call it on each one of them.

The behavior you want can be achieved better using .on ( http://api.jquery.com/on/ )

Quick example, given this html:

<div class="button-container">
  <input class="interview-yes" id="id1" type="submit" value="Yes"">
  <input class="interview-yes" id="id2" type="submit" value="Yes"">
  <input class="interview-yes" id="id3" type="submit" value="Yes"">
</div>

You can use this jquery code:

$('.container').on('click','.interview-yes', function(e){
  alert($(this).attr('id'));
}

As an added benefit, using this strategy, the event handler still works if you populate the container later via ajax/js.

Upvotes: 0

Related Questions