Adam Bazzal
Adam Bazzal

Reputation: 13

How to use multiple IDs in one function

How to use it on multiple ids such that when #more1 is clicked , #details1 will appear. And when #more2 is clicked , #details2 will appear? Note that I want it only using one function. Thank U.

$(document).ready(function () {
    $('#more1,#more2').click(function () {
        $('#details1,#details2').slideToggle();
    });
});

Upvotes: 1

Views: 2006

Answers (3)

Thomas F
Thomas F

Reputation: 2036

You can use a more general selector: $('[id^="more"]'). This will select all items that have an id that starts with "more", and will have a click event tied to them.

Then you can use the number in the id property and use it to build the id of the target.

$('[id^="more"]').click(function()
{
    let id = $(this).attr('id');
    let num = /\d+/.exec(id)[0];
    $('#details' + num).slideToggle();                  
});

$(document).ready(function()
{
    $('[id^="more"]').click(function()
    {
        let id = $(this).attr('id');
        let num = /\d+/.exec(id)[0];
        $('#details' + num).slideToggle();                  
    });    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <button id="more1">One</button>
  <span id="details1">Each Section</span>
</div>
<div>
  <button id="more2">Two</button>
  <span id="details2">Is Independent</span>
</div>
<div>...</div>
<div>
  <button id="more25">Twenty Five</button>
  <span id="details25">Of all the others</span>
</div>

Upvotes: 1

user14860400
user14860400

Reputation:

You can use for loop

$(document).ready(function()
{
    var length = 9; // any number you need
    for (var i = 0; i < length; i++ ) {

        $('#more' + i).click(function()
        {
           $('#details' + i).slideToggle();                  
        });    
    }
                              
});

Upvotes: 0

Abbas Akhundov
Abbas Akhundov

Reputation: 562

You can check the id of the current item and act accordingly:

if($(this).attr('id') == 'more1') $('#details1').slideToggle();   

A more elegant solution would be:

$('#details' + $(this).attr('id')[$(this).attr('id').length - 1]).slideToggle();

The last one uses the fact that the numbering in the ids is similar, and if you have less than 10 such ids it will work properly.

Upvotes: 0

Related Questions