开发者

Does a plugin exist that creates an "Other" option in dropdown menus, and creates a textbox for alternative input when Other is selected?

I have a multi-page form with many dropdown select boxes. Most of those boxes need to have an "Other" field and then a way to enter content that is not one of the select values. When the form is submitted, if "Other" is selected, the "other" content should be saved into the database in place of the dropdown menu.

Is there a plugin or script that has already been written that can do this for me easily? A lot of my fields are created dynamically and must be edited later on (using a nested form jquery plugin) so writing code that applies to all of them (without writing a specific function for each field) has been tough for me.

If I can't find a suitable plugin I will probably use the Dojo dijit Combobox, and while that accomplishes exactly what I am looking for, the ideal for my users would be a select box plugin that has an "Other" option in the dropdown, and when "Other" is selected a text box would appear for users to fill out. When the field is being edited, it would also need to populate the dropdown or text-box appropriately based on the value stored in the database. D开发者_JS百科oes something like this exist, either in javascript/jquery/prototype/other, or a rails 3 plugin or gem? Thanks so much!

Edit: I will most likely use FlexBox if I can't find something with a separate text area - but I'm still looking for a separate-text-area solution!


I've thrown together a small script which might do what you want: http://jsfiddle.net/nHh3C/ Could definitely still be improved, but I guess you get the idea. Might actually use this myself :D

Here's the JS:

$('select').each(function(i, select){
    if (!$(select).data('name')) {
        $(select).data('name', $(select).attr('name'));
    } 
    $(select).change(function(){
        if ($(this).val() == 'other') {
            $('<input/>', {
                'name' : $(this).attr('name')
            }).insertAfter($(this)); 
            $(this).attr('name', '');
        } else {
            $('input[name='+$(this).data('name')+']').remove();
            $(this).attr('name', $(this).data('name'));
        }
    });
});

EDIT Ah, and incase this wasn't clear — it uses jQuery. Just change the select selector to what you need and you should be set. Wouldn't be hard to wrap this in a plugin either.

EDIT 2 With rails you should be probably able to do something like this (probably nicer in a helper) to generate the select:

select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] } << ['Other', 'other'])

For the edit view you could then just check if the value is contained in the select values and if not, print an additional input field and set the select to pre–select the 'other' options. And you should handle the JS to match the situation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜