jQuery - toggle display of a string of comma deliminated values

Within a table I have a column which contains a list of values which are comma deliminated.

The action I want to achieve is that clicking on the deliminated text will 'roll-up the text to display just the first value. Clicking again would once again display all values.

My intent is to use a + and - sign to show the state.

String example: "Red, Blue, Green"

Collapsed display: + Red

Expanded display: - Red Blue Green

Answers


Given an element with id=rgb:

$('#rgb').click( function() {
    var $this = $(this);
    var text = $this.text();
    if( text[0] == '+' ) {
        $this.text($this.data('hiddenText'));
    } else {
        $this.data('hiddenText', text);
        var index = text.indexOf(',');
        if(index >= 0) {
            $this.text('+' + text.substr(1,index-1));
        }
    }
});

On fiddle


Version where +/- is not part of element: fiddle

$('#rgb').click( function() {
    var $this = $(this);
    var text = $this.text();
    var index = text.indexOf(',');
    if( index < 0) {
        if ($this.data('hiddenText') !== undefined) {
            $this.text($this.data('hiddenText'));
        }
    } else {
        $this.data('hiddenText', text);
        $this.text(text.substr(0,index));            
    }
});

Need Your Help

Alertbox with list selection items remains empty

android android-alertdialog android-dialog

I would like to check a number of Spinner controls in the Onclick event of a few buttons (if the user moves away from the Activity), and if one or more were not filled out, display a warning messag...

How to disable Write access to a mysql table via sql command or phpMyAdmin for my xoops website issue

php mysql security

I have a website based on php+xoops+mysql5.1, I recently found my xoops_users table which stores members of the website is being attacked: there are new rows inserting into this table with random