Question

Hi I am having a piece of code. Here I am toggling my table based on the class name which I have hardcoded over here. I want to pass my class name as a variable in order to toggle it.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function alok(){
    $(".b:not(:first)").toggle();
}
</script>
</head>
<body>


<table>
<tr  class="b" onclick=alok()><td>qw</td></tr>
<tr  class="b"><td>alok</td></tr>
<tr  class="b"><td>verma</td></tr>
<tr  class="c" onclick=alok()><td>qw</td></tr>
<tr  class="c"><td>alok</td></tr>
<tr  class="c"><td>verma</td></tr>

</table>

</body>
</html>
Was it helpful?

Solution

Thanks guys for looking into it... anyways I solved it.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function alok(obj){
var s= $(obj).attr('class');

    $("."+s+":not(:first)").toggle();
}
</script>
</head>
<body>


<table>
<tr  class="b" onclick=alok(this)><td>qw</td></tr>
<tr  class="b"><td>alok</td></tr>
<tr  class="b"><td>verma</td></tr>
<tr  class="c" onclick=alok(this)><td>qw</td></tr>
<tr  class="c"><td>alok</td></tr>
<tr  class="c"><td>verma</td></tr>

</table>

</body>
</html>

OTHER TIPS

You should make use of jQuery here.

$(document).on('click', 'tr', function () {

    var elemClass = $(this).attr('class');
    $('.' + elemClass + ':not(:first)').toggle();

});

I've wrote a fiddle - check it out.

http://jsfiddle.net/Wc5km/

As you're including jQuery in your document, it'd be a shame not to make use of it. Cleaner, more readable and it gets rid of that ugly inline onclick!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top