Jennifer
Jennifer

Reputation: 1331

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 clicked only the dtxt1 will slide, and if lblBtn2 is clicked it will show the dtxt2.

    $(document).ready(function(){
      $("#lblBtn1").click(function(){
      $("#dtxt1").slideToggle();
      });
      $("#lblBtn2").click(function(){
      $("#dtxt2").slideToggle();
      });
   });

html

<lbl id="lblBtn1">&#43;</lbl>Menu1 
    <div id="dtxt1">ASDFGH</div>

<lbl id="lblBtn2">&#43;</lbl>Menu2 
    <div id="dtxt2">QWERTY</div>

Upvotes: 0

Views: 62

Answers (4)

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

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();
    });
});

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

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();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<lbl id="lblBtn1">&#43;</lbl>Menu1 
    <div id="dtxt1">ASDFGH</div>

<lbl id="lblBtn2">&#43;</lbl>Menu2 
    <div id="dtxt2">QWERTY</div>

Upvotes: 0

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

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

This will work for all the labels

Or try click event on <lbl> tags

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

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

Upvotes: 0

Related Questions