Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a value (which is get by .text() when a li is clicked) as a selector to hide some div

Tags:

jquery

i have a ul li list like

<ul class="dropdown-menu" id="dropdown">
   <li><a id='l1' href='javascript:void(0);'>batch1</a></li>
   <li><a id='l2' href='javascript:void(0);'>batch2</a></li>
   <li><a id='l3' href='javascript:void(0);'>batch3</a></li>
   <li><a id='l4' href='javascript:void(0);'>batch4</a></li>
   <li><a id='l5' href='javascript:void(0);'>batch5</a></li>
   <li><a id='l6' href='javascript:void(0);'>batch6</a></li>
</ul>

now, i can get the text value of every li, the problem is, i cannot use the text value as selector.what i want to do is: i have some div(id are "batch1, batch2...batch6"),which i want to hide if a li is clicked(except clicked li). code are=

html:

<div id="batch1"></div> 
<div id="batch2"></div> ......

jquery:

$(document).ready(function(e) {
    $('body').click(function(event) {

    if($(event.target).is('#l1')) {
       var id = "'#"+$('#l2').text()+"'";
       $(id).hide();
    }
});
});

what should i do. i am trying about 24 hours but still in dark. and thanks in advance

like image 996
Shoshi Avatar asked Oct 08 '22 15:10

Shoshi


2 Answers

You should add a common class to all #batch1, #batch2 elements so you can target them all at once..

Then use the id as the exception...

Html

<div id="batch1" class="batch"></div>
<div id="batch2" class="batch"></div>

javascript

$('#dropdown').on('click','a', function(e){
    e.preventDefault();
    var id = '#' + $.trim( $(this).text() ); // create the id based on the text

    $('.batch').hide(); // hide all batch elements
    $(id).show(); // show the one that corresponds to the clicked li
});

Demo at http://jsfiddle.net/A5Vxm/

like image 160
Gabriele Petrioli Avatar answered Oct 12 '22 10:10

Gabriele Petrioli


$('body').click(function(event) {
    if(event.target.id  == 'l1' ) {
       var id = "#" + $.trim( $('#l2').text() );
       $(id).hide();
    }
});​

DEMO

But if you divs are dynamic that means added into DOM after page load then try

    $('body').on('click', 'a', function(event) {
        event.preventDefault();
        if(event.target.id  == 'l1' ) {
           var id = "#" + $.trim( $('#l2').text() );
           $(id).hide();
        }
    });​
like image 38
thecodeparadox Avatar answered Oct 12 '22 10:10

thecodeparadox