tags:

views:

389

answers:

1

The current HTML SELECT tag works great for me except for one thing. Is it possible to implement toggling on the current item.

If I have a current selection, I'd like to click it again and "de-select" it. It doesn't work that way now, it simply keeps the current selection "selected".

It seems that I need to know the "previous" selection along with the "current" selection and compare the 2 to see if I need to "de-select" everything. How do I get the previous selection, all I know about is "selectedIndex" which is the current selection.

Is there a way?

A: 

To accomplish this you might use a little bit of javascript as follows. I have tested and it seems to work as you requested. I am being verbose for readability, but you can clean once you have it working for you.

<script language="JavaScript" type="text/javascript">
    function toggleSelectedValue() {

        var selObj = document.getElementById('myList');
        var selIndex = selObj.selectedIndex;
        var selValue = selObj.options[selIndex].value;
        var prevSelValue = document.getElementById('trackSelectedValueHiddenField').value;

        if (selValue == prevSelValue) {

            //Delect "all" items
            selObj.selectedIndex = -1;
            document.getElementById('trackSelectedValueHiddenField').value = 0;
        }
        else {setSelectedValue();}

    }
    function setSelectedValue() 
    {
        var selObj = document.getElementById('myList');
        var selIndex = selObj.selectedIndex;
        document.getElementById('trackSelectedValueHiddenField').value = selObj.options[selIndex].value;
    }
    </script>

</head>
<body>
<div id="wrapper">
    <div id="contentDiv" style="height:686px; border: solid 1px red;">
    <select multiple="multiple" id="myList" onclick="toggleSelectedValue()">
        <option value="1">Test</option>
        <option value="2">Test</option>
        <option value="3">Test</option>
    </select>
    <input type="hidden" id="trackSelectedValueHiddenField" value="0" />
    </div>
</div>
</body>
</html>
PortageMonkey