开发者

how to prevent html select (dropdown) box options from displaying

I was trying to attach to the onclick and the onchange events, but haven't met with a lot of success.

The ultimate goal is to overlay a div or a ul and display the options where the user can click; this will then change the option on the select box. Is it possible to do this?

I've tried out some code here. The non-working example can be found below:

http://jsfiddle.net/deostroll/Yed7p/1/

The markup for the dropdown:

<select>
    <option value="000">Select A Country</option>
    <option value="001">India</option>    
    <option value="002">Australia</option>    
    <option value="003">United States Of America</option>
    <option value="004">Great Britan</option>
    <option value="005">Zimbabwe</option>
    <option value="006">Newzeland</option>    
</select>

Here is the javascript:

$(function(){
    $('select').click(function(e){      
        var ul = document.createElement('ul');
        $(this).children().each(function(){
    开发者_JAVA百科        var li = document.createElement('li');
            $(li).html($(this).text());
            $(li).data("value", $(this).val());
            $(ul).append(li);
        });
        $('body').append(ul);
        var cordinates = $(this).offset();
        $(ul).offset({top:cordinates.top + 10 + $(this).height(), left:cordinates.left});
        $(ul).show('slow');
        e.preventDefault();
    }); 
});

The problem here is that when I click on the dropdown the options are shown by default. I am trying to prevent that. And btw i was doing all this exercise on google chrome browser. Later I intend to test other browsers too. I know that there are libraries that do this, but I just wanted to know the technique used.


AFAIK, there is no way to do that. Your best bet is to use a custom dropdown (plugin or your own implementation).

The ultimate goal is to overlay a div or a ul and display the options where the user can click; this will then change the option on the select box. Is it possible to do this?

Btw, from your question, unless you want to change the look of dropdown box, you can stick to the default behavior


The procedure you described is a workaround for making HTML forms more beautiful and is almost common. For example, a lot of designers create their own checkboxes and hook them with JavaScript to the underlying <input type='checkbox' elements on their form. However, your way of doing it is a little abnormal.

Do not try to overlay your select element with a div or ul. Simply create a div, or ul as something that the user sees, and via JavaScript, try to imitate a drop down list. Whenever user clicks on any item in your list, get the value and set your select's value accordingly.

In other words, instead of trying to hook div or ul into select events, match select with click events of div or ul.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜