Marcin Doliwa
Marcin Doliwa

Reputation: 3659

How to set click event on multiple buttons

I have multiple buttons with ids like: #recent_post_button_54,#recent_post_button_55 etc.

When I click button #recent_post_button_54 I want it to toggle corresponsing #recent_post_content_54 div.

My code is:

jQuery(document).ready(function($) {
  var buttons = $('.recent_post_header button');
  for (var i = 0; i< buttons.length; i++) {
    var id = (buttons[i].id).match(/\d+$/)[0];

    $("#recent_post_button_"+id).click(function() {
      console.log("I've clicked #recent_post_button_"+id);
      $("#recent_post_content_"+id).toggle();
    });
  }
});

I have three buttons with ids 54,52,50. But with this code I get I've clicked #recent_post_button_50 for all buttons, and all buttons toggle only the last content div with id 50.

What is wrong with this code?

Upvotes: 0

Views: 66

Answers (3)

user5505124
user5505124

Reputation: 1

Use common class for all these buttons like as shown in this link (I have created a plunker: http://plnkr.co/edit/1xFhmDSo8LUCztDQF9ma). You can modify the selector as per your requirement. Assuming you have buttons like this you can have you code as shown below:

 <button type="button" id="recent_post_button_54" class="dynamicIdButton">Button1</button>
<button type="button" id="recent_post_button_52" class="dynamicIdButton">Button1</button>
<button type="button" id="recent_post_button_50" class="dynamicIdButton">Button1</button>

<script>
  $(".dynamicIdButton").click(function() {
  alert('I have clicked! : ' + this.id);
});
</script>

Upvotes: 0

Anonymous0day
Anonymous0day

Reputation: 3042

Try this solution using event delegation

jQuery(document).ready(function($) {
  
  
  $('.recent_post_header').click('button' , function(evt){
    
    var $but = $(evt.target);
    var id = $but.attr('id');

        alert( "I've clicked #recent_post_button_" +  id);
    
    $("#recent_post_content_"+ id).toggle();
    
  })
  
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='recent_post_header'>
  <button id='54'>button 54</button>  
  <button id='52'>button 52</button>  
  <button id='50'>button 50</button>  
</div>
<div id='recent_post_content_52'>
  post 52
</div>

<div id='recent_post_content_50'>
  post 50
</div>

<div id='recent_post_content_54'>
  post 54
</div>

Upvotes: 0

DinoMyte
DinoMyte

Reputation: 8858

Use ^(starts with) expression on the id. Also, to get the corresponding target div, replace the word "post" with "content".

$("input:button[id^='recent_post_button']").click(function()
{
      var id = $(this).attr("id");

    var contentID = id.replace("button","content");
       $("#" + contentID).toggle();

});

http://jsfiddle.net/nzyaq8ma/

Minified:

$("input:button[id^='recent_post_button']").click(function()
{
      $("#" + $(this).attr("id").replace("button","content")).toggle();      
});

Upvotes: 3

Related Questions