2

I have a table of items being pulled from a database. The items are laid out as follows:

(+) 02/04/2014
Item 1
(+) 02/05/2014
Item 2
Item 3
(+) 02/06/2014
Item 4
Comment for item 4
Item 5

The items under the dates are hidden, when the user clicks the (+) sign, it will show the items below it and replace the (+) with a (-) to hide the items.

The HTML roughly looks as follows:

<table>
<tr><td>(+)</td><td>02/04/2014</td></tr>
<tr id="id_1" class="hidden"><td colspan="2">Item 1</td></tr>
<tr><td>(+)</td><td>02/05/2014</td></tr>
<tr id="id_2" class="hidden"><td colspan="2">Item 2</td></tr>
<tr id="id_3" class="hidden"><td colspan="2">Item 2</td></tr>
<tr><td>(+)</td><td>02/06/2014</td></tr>
<tr id="id_4" class="hidden"><td colspan="2">Item 4</td></tr>
<tr id="comment_id_4" class="hidden"><td colspan="2">Comment for item 4</td></tr>
<tr id="id_5" class="hidden"><td colspan="2">Item 5</td></tr>
</table>

The only way I've been able to think of doing it is by dynamically generating a JavaScript function by looping through the records again and adding this a href to the plus sign:

<a href="#" onclick="toggle(242014);return false">(+)</a>

And here's a sample of the generated JavaScript:

 function toggle(id) {
    switch (id) {
    case 242014:
        $("#id_1").toggle();
        break;
    case 252014:
        $("#id_2").toggle();
        $("#id_3").toggle();
        break;
    case 262014;
    $("#id_4").toggle();
    $("#comment_id_4").toggle();
    $("#id_5").toggle();
    break;
    }

It works, but it's ugly. Is there a more elegant way of doing this?

Thanks.

3
  • check your HTML markup, it is not valid and you shouldn't use IDs here Commented Feb 5, 2014 at 12:23
  • isn't TD closed before it's opened on the colspan lines? Commented Feb 5, 2014 at 12:26
  • Yeah, I threw that together fast, my bad as they say...fixed. Commented Feb 5, 2014 at 12:39

2 Answers 2

3

I would add an extra attribute to identify the affected rows for example:

<tr colspan="2" id="id_2" date="12122014" class="hidden" >

then the javascript would be

function toggleByDate(date){ $('tr[date="'+date+'"]').toggle(); }

more info about the useful attributes selector in jQuery here

Sign up to request clarification or add additional context in comments.

Comments

2

this is really ugly:

<tr colspan="2" id="id_2" class="hidden">Item 2</td></tr>

you do not open <td> but close it, also colspan="2" must be inside of <td>

1 Comment

Oops, I typed that out real fast. The HTML I am working on is valid, will fix the post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.