Geeks With Blogs
X Lines 1 Goal
Selecting Items in a list using DIVs instead of Radio Buttons

Problem: Radio buttons cannot be styled using CSS. Another problem is that they simply f*** up your design if used incorrectly. They are also not very useful if you would like a user to be able to click on a large item in order to select it.

Solution: A solution to this problem would be to allow the user to click on whole DIVs in order to select an item. This is done using some javascript, CSS and a hidden textbox. This is how it's done using ASP VB and Javascript. Obviously this can be done using other Server Side languages as the main work will be done by Javascript. So...

This is the javascript needed.

<script type="text/javascript">
    var selected = 0; //holds the selected div id... set to be the first selected item (in this case - 0)
    
    function selectDIV(newid)
    {
        document.getElementById('div' + selected).className = 'item'; //change previously selected item CSS
        selected = newid; //set 'selected' as the new id
        document.getElementById('div' + selected).className = 'itemselected'; //change the newly selected item CSS
        document.getElementById('selecteddivid').value = selected; //set value of hidden textbox to selected div id
    }
</script>

The highlighted part in this code is the most important thing. The 'selected' variable holds the ID Number of the selected DIV. It is important to set it by default as the item selected when the page loads.

This is the HTML/ASPVB code needed.

    <% for i = 0 to 5
        if i = 0 then
            myclass = "itemselected"
        else
            myclass = "item"
        end if
       
        divid = "div" & i
    %>
        <div class="<%= myclass %>" id="<%= divid %>" onclick="selectDIV(<%= i %>)">
            To select DIV #<%= i %> click here.
        </div>
    <% next %>
   
    <form action="default.asp" method="post">
        <input type="hidden" id="selecteddivid" name="selecteddivid" value="0" />
        <input type="submit" value="SAVE" />
    </form>

In this case, I used a loop from 0 to 5 to generate 6 divs. The ID of each DIV is 'divx' where x is a number from the loop. The onclick event calls the selectDIV function which we did above. As you can see a hidden textbox 'selecteddivid' is created here which will hold the selected div's id. This can later be read using request.form("selecteddivid") after the form posts.

Conclusion: Javascripts like this are easy to create and will help you create better-looking webpages by allowing the user to interact better with your website.


Code example will be coming soon.

Posted on Monday, December 1, 2008 9:20 AM ASP VB , Javascript | Back to top


Comments on this post: Selecting Items in a list using DIVs instead of Radio Buttons

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © xlinesonegoal | Powered by: GeeksWithBlogs.net