Jquery dynamically update “other” option in select

后端 未结 2 685
情深已故
情深已故 2021-02-10 14:07

I\'m working on a project that will be using a lot of select menus to enter various data. I\'d like to include an \'other\' option directly in the select that will trigger a sim

相关标签:
2条回答
  • 2021-02-10 15:02

    This will get you started. This will add the functionality to any select on the page, appending a new value to the select (and leaving other still available in case a mistake has been made).

    $(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>');
            }
        });
    });
    
    0 讨论(0)
  • 2021-02-10 15:02

    I actually solved a problem very similar to this and ended up writing a jQuery plugin (jQuery.otherDropdown) to collect an 'other' response for a select dropdown. It's on GitHub and npm. I'll break down my approach so you can implement it your own way.

    This idea is a perfect use case for jQuery in my opinion.

    The basic components

    Listen for when your 'other' options is slected

    Add a .change() event binding on the select input.

    $('select').change( function() {
        if(this.value === 'other') {
            // Your logic here to for when/how to prompt for user input
        }
    });
    

    Listen for user input

    If you choose an text input instead of a prompt (which may be a better user experience), listen for the blur event

    // 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
    }
    

    Add the new option

    No matter how you choose to prompt the user for the value, adding it is as simple as creating the element via jQuery and appending it. Lastly you'll probably want to focus the value, which can be done with .val()

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

    Example

    All of these ideas are wrapped in this plugin and might a good example you can play with and reuse to work how you need. You can see it working here

    /**
     * @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 );
        });
    };
    
    0 讨论(0)
提交回复
热议问题