Skip to content Skip to sidebar Skip to footer

Toggling Many Div Id

I have many div to hide/show when the user clicks the toggle button. My toggle button is working but is there a shorter way to write the codes? It should be, when lblBtn1 is clicke

Solution 1:

try this:

// Shorter $(document).ready
$(function () {
    // Use attribute selector for both of your #id because they are like each other..
    $("[id^=lblBtn]").click(function () { // or $("#lblBtn1, #lblBtn2").click(function () { // Use next function to find next div to slideToggle because they are next to each other (siblings)
        $(this).next('div').slideToggle();
    });
});

Solution 2:

You can use id start with selector or tagname selector to target all label element along $(this).next() to target desired div elements:

$("[id^=lblBtn]").click(function(){//or $("lbl").click(function(){
   $(this).next().slideToggle();
});

working Demo

Solution 3:

$('[id^="lblBtn"]').click(function(){
    $(this).next().slideToggle();
});

This will work for all the labels

Or try click event on <lbl> tags

Solution 4:

This will target the desired #dtxt even if it is not directly next to #lblBtn

$('[id^=lblBtn]').click(function() {
    var num = $(this).attr('id').replace('lblBtn', '');
    $('[id=dtxt' + num + ']').slideToggle();
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><lblid="lblBtn1">&#43;</lbl>Menu1 
    <divid="dtxt1">ASDFGH</div><lblid="lblBtn2">&#43;</lbl>Menu2 
    <divid="dtxt2">QWERTY</div>

Post a Comment for "Toggling Many Div Id"