JQuery - Multiple Select Options

前端 未结 9 712
时光取名叫无心
时光取名叫无心 2020-12-07 15:53

I am trying to grab all selected items in the following select multiple and separate them by a comma. The code is below:


                        
    
提交评论

  • 2020-12-07 16:13

    On a multiple select element, the val command of the select element will return an array of the selected options values. If no values are present, the text of the element is used:

    var output = $("#ps-type").val().join(', ');
    

    update: However, when there are no selected options val() returns null not an empty array. One way to get around this:

    var output = ($("#ps-type").val() || []).join(', '); 
    

    You can play around with it in this demo I put together.

    From the docs:

    In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.

    0 讨论(0)
  • 2020-12-07 16:13

    Here you go:

    var result = new Array();
    
    $("#ps-type option:selected").each(function() {
        result.push($(this).val());
    });
    
    var output = result.join(", ");
    
    0 讨论(0)
  • 2020-12-07 16:22
    var list = "";
    $('#ps-type option:selected').each(function(){
      list += this.value + ", ";
    });
    return list.substr(0, list.length - 2);
    
    0 讨论(0)
  • 2020-12-07 16:25

    You can use the :selected selector, and the inline $.map() function as part of your chain.

    $("option:selected").map(function(){ return this.value }).get().join(", ");
    
    0 讨论(0)
  • 2020-12-07 16:25

    Try this:

        var List = new Array();
        $('#ps-type option:selected').each(function () {
           if ($(this).length) {
                  var sel= {
                      name: $this.text()
                  }
           }
           List.push(sel);
        });
        var result = List.join(', ');
    
    0 讨论(0)
  • 提交回复
    热议问题