multiple select element - onchange

后端 未结 9 1981
栀梦
栀梦 2021-02-18 22:50

I have a select element that allows for multiple selections. I\'d like to display the selected values in another part of the page (in a div or something) as the user makes chang

相关标签:
9条回答
  • 2021-02-18 23:06

    In your fiddle, I just used .val(). This returns an array

    JSFiddle Link

    $(function() {
        $('#fruits').change(function() {
            console.log($(this).val());
        }); 
    });
    
    0 讨论(0)
  • 2021-02-18 23:09

    This works:

    var MyControl = document.getElementById('Control_ID');
    var newValue = MyControl[MyControl.selectedIndex].value;
    

    Of course, Control_ID is the ID of the select control.

    0 讨论(0)
  • 2021-02-18 23:10

    .val() on a multiple select returns an array.

    See the snippet below as an example:

    $(function() {
        $('#fruits').change(function(e) {
            var selected = $(e.target).val();
            console.dir(selected);
        }); 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select multiple="true" id="fruits">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="mango">Mango</option>
        <option value="grape">Grape</option>
        <option value="watermelon">watermelon</option>
    </select>

    0 讨论(0)
  • 2021-02-18 23:10

    You could use blur instead of change, so that the select is only processed once, rather than on each selection. http://jsfiddle.net/2mSUS/3/

    0 讨论(0)
  • 2021-02-18 23:21

    $(function() {
        $('#fruits').change(function(e) {
            var selected = $(e.target).val();
            console.dir(selected);
        }); 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select multiple="true" id="fruits">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="mango">Mango</option>
        <option value="grape">Grape</option>
        <option value="watermelon">watermelon</option>
    </select>

    0 讨论(0)
  • 2021-02-18 23:22

    I'm doing a form submit. My template helper looks like this:

     'submit #update': function(event) {
        event.preventDefault();
        var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
        var array_opts = Object.values(obj_opts);  //convert to array
        var stray = array_opts.map((o)=> o.text ); //to filter by: text, value or selected
        //stray is now ["Test", "Milk Free"] for example, depending on the selection
        //...do stuff...
    }
    

    You could use a similar pattern for 'onchange'

    0 讨论(0)
提交回复
热议问题