user2526777
user2526777

Reputation: 75

jquery hide/show div based on span text

need some help with this. I have a span element where the text changes based on a selection from another drop-down element:

<span class="drop link" id="title-tagger-20965969" style="cursor:default;text-decoration:underline;">...ng calls or email - 2E1</span>

Basically I want to show the corresponding div ID (as below) that matches the text code on the end of the span element text like the example above (2E1)

<div id="changingArea">
<div id="2E1" class="desc">TEXT 2</div>
<div id="2E2" class="desc">TEXT 2</div>
<div id="2E3" class="desc">TEXT 3</div>
</div>

I also want all all the 'changingArea' divs hidden unless the span element contains the div id as text.

Thanks in advance

Upvotes: 1

Views: 3790

Answers (2)

Greenhorn
Greenhorn

Reputation: 1700

Try this:

$('span').click(function(){
var txt = $(this).text();
$('.desc').hide(); //hide all divs
var id;
$("div.desc").each(function(){
id=$(this).attr("id");
    if(txt.indexOf(id)>=0){
    $(this).show();
    }
})   
});

Fiddle Here

Upvotes: 0

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

I will suggest you to place the id of the div in the span attribute and hide/show based on the id

$('span').click(function(){
    var id = $(this).attr('data-id');
    $('.desc').hide(); //hide all divs
    $('#'+id).show(); //show div based on id
});

FIDDLE

UPDATE

If you will always have text in the span in this format ...ng calls or email - 2E1 where after - will be the id than you can do it like this

$('span').click(function(){
    var html = $(this).html();
    var split = html.split('-');
    $('.desc').hide(); //hide all divs
    $('#'+$.trim(split[1])).show(); //show div based on id
});

FIDDLE

Upvotes: 1

Related Questions