Reputation: 105
I have a html code two divs - one is a button and second is rectangle. The rectangle is hidden and I want to show it, when the button is clicked. The problem is, that I have many of those buttons and rectangles. Each one has the class:
<div class="navid-1">Sonething</div>
and those rectangles
<div class="topicid-1">long text</div>
Now I need some function, that will select something with class navid-*, get that number, and show topicid-[that number]. And I don't know, how to do that. Additionally, it would be nice to hide that rectangle, which is currently visible. (Like swap them). Thanks.
Upvotes: 3
Views: 8726
Reputation: 1396
You could use a regex to get the numbers in the end of the class
attribute. Something like this:
$('[class^=navid-]').on('click', function() {
var num = $(this).attr('class').match(/\d+$/)[0];
$('.topicid-'+num).show();
});
Upvotes: 8
Reputation: 3753
instead of setting classes like this, you can set custom data attributes, like
<div class="topicid-1" data-topic="1">long text</div>
or you could call the function with a parameter
<div class="topicid-1" onclick="showTopic(1)">long text</div>
Upvotes: 4
Reputation: 318182
target all buttons with the attribute starts with selector, then slice of the last character from the classname, making sure you don't have multiple classes etc. and use it to find the related rectangle :
$('[class^="navid-"]').on('click', function() {
$('.topicid-'+this.className.slice(-1)).show();
});
to hide visible rectangles, target all of them :
$('[class^="topicid-"]').hide()
and place that before you show the current one:
$('[class^="navid-"]').on('click', function() {
$('[class^="topicid-"]').hide()
$('.topicid-'+this.className.slice(-1)).show();
});
Upvotes: 1