Jquery动态更新下拉框中的“其他”选项

4
我正在处理一个需要使用许多下拉菜单输入不同数据的项目。我想在下拉菜单中直接包含“其他”选项,以触发简单对话框并允许用户输入自定义值(如果适用),类似于以下JavaScript代码:
<script type="text/javascript" language="javascript">
    function chkother(fld,len,idx) {
        if ((idx+1)==len) {
            other=prompt("Please indicate 'other' value:");
            fld.options[idx].value=other;
            fld.options[idx].text=other;
        }
    }
</script> 

这个与select配合使用:

<select onchange="chkother(this,this.options.length,this.options.selectedIndex)" name="example" id="example" class="formSelect">
<option  value=""></option>
<option  value="yes">yes</option>
<option  value="no">no</option>
<option  value="other">other</option>
</select>

它会弹出一个提示框,用户可以在里面更新选项。

我想用jquery做类似的事情,以便扩展功能并学习一些jquery,但是我遇到了一些困难。

2个回答

9

这将帮助您入门。它将为页面上的任何选择添加功能,将一个新值附加到选择中(并在发生错误时保留其他仍可用的选项)。

$(function() {
    $('select').change( function() {
        var value = $(this).val();
        if (!value || value == '') {
           var other = prompt( "Please indicate other value:" );
           if (!other) return false;
           $(this).append('<option value="'
                             + other
                             + '" selected="selected">'
                             + other
                             + '</option>');
        }
    });
});

@tvanfosson 这个解决方案看起来很棒,但是当我将它添加到我的页面上时,什么也没有发生。如果我理解正确的话(我不太懂JavaScript或jQuery),它会搜索所有选择器以查找缺失值或空值(""),并通过提示框替换该值。 - user238680
抱歉,我一定是犯了一个错误。这个函数很棒,非常感谢! - user238680
它的工作方式是当选择改变时,它会检查新值。如果为空,则提示(与您先前的解决方案相同)输入新值,并从该值构造所选选项并将其附加到已更改的选择中。 - tvanfosson

3
我曾经解决过一个类似的问题,最终编写了一个jQuery插件(jQuery.otherDropdown)来收集选择下拉框中的“其他”响应。它在GitHubnpm上。我将分解我的方法,以便您可以按照自己的方式实现它。
在我看来,这个想法是jQuery的一个完美用例。
基本组件
监听当选择了“其他”选项
在选择输入框上添加一个.change()事件绑定。
$('select').change( function() {
    if(this.value === 'other') {
        // Your logic here to for when/how to prompt for user input
    }
});

监听用户输入

如果您选择文本输入而不是提示框(这可能会提供更好的用户体验),请监听模糊事件。

// listen to a text area
$('input').blur( function() {
    if(this.value !== '') {
        // Logic to add the new option to the select
    }
});

// or bring up a prompt dialog
var value=prompt("Please indicate 'other' value:");
if(this.value !== '') {
    // Logic to add the new option to the select
}

添加新选项

无论您选择何种方式提示用户输入值,添加新选项都非常简单,只需通过jQuery创建元素并将其附加即可。最后,您可能需要聚焦该值,可以通过使用 .val() 来完成。

var $option = $('<option value="' + value + '">' + value + '</option>');
$('select').append($option);
$('select').val(value);

示例

所有这些想法都包含在这个插件中,它可以作为一个很好的示例供您使用和重复利用,以满足您的需求。您可以在此处看到它的工作。

/**
 * @name jquery.otherdropdown
 * @description A small jQuery plugin to support a text area when selecting an 'Other' option in a dropdown
 * @version 1.0.2
 * @author Jonathan Stassen <jstassen.com>
 * @see https://github.com/TheBox193/jquery.otherdropdown
 */
$.fn.otherDropdown = function(options) {
    var $this = this;
    // Allow a different name/value to trigger, default to 'other'
    var opts = $.extend({}, {value: 'other'}, options);
    opts.name_lower = opts.value.toLowerCase();
    opts.name_upper = opts.value.charAt(0).toUpperCase() + opts.value.slice(1);
    opts.placeholder = opts.placeholder || opts.name_upper;

    // Bind to all change events
    $this.change( function(ev){

        // Swap in the text area if our 'other' option was chosen
        if (this.value === opts.name_lower || this.value === opts.name_upper) {
            $this.hide().after( $textInput );
            $textInput.focus();
        }
    });

    // Prepare our text input
    var $textInput = $('<input type="text" class="otherdropdown" placeholder="' + opts.placeholder + '" />');

    // Allow custom classes on the text input
    if (opts.classes) {
        $textInput.addClass(opts.classes);
    }

    // Bind to blur to swap back to select dropdown
    $textInput.blur( function(ev) {
        var value = this.value;
        this.value = '';
        this.remove();
        $this.show();

        if (value === '' || value === opts.name_lower || value === opts.name_upper) {
            return;
        }

        // If something was typed, create a new option with that value
        var $searchedOption = $this.children('[value="' + value + '"]');

        // If value doesn't exist, added it.
        if ( $searchedOption.length < 1 ) {
            var $option = $('<option value="' + value + '">' + value + '</option>');
            $this.append($option);
        }

        // Focus the value
        $this.val( value );
    });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接