how to iterate through multiple select options with jquery

后端 未结 6 2108
走了就别回头了
走了就别回头了 2021-02-18 13:22

I was just wondering if it\'s possible to go through multiple select options and get their values and text(if one is selected get the value and text, if 2 is selected get both o

相关标签:
6条回答
  • 2021-02-18 13:44

    for optgroups...

    $("select[id^='desu']").children('optgroup').children('option:selected').each( 
        function(id, element) {
            document.write(element.title);
        }
    );
    
    0 讨论(0)
  • 2021-02-18 13:53

    https://jsfiddle.net/kmgoddard/Lfkvm3ar/4/

    $("#mybutton").click(function(){
    list = new Array();
    $('select > option:selected').each(function() {
    
      list.push($(this).val());
    
    });
     alert(list.toString());
    });
    
    0 讨论(0)
  • 2021-02-18 13:54

    This will alert all the selected options' text and values (for all selects on the page):

    $('select > option:selected').each(function() {
        alert($(this).text() + ' ' + $(this).val());
    });
    

    See Core/each and Selectors/selected:

    http://docs.jquery.com/Core/each

    http://docs.jquery.com/Selectors/selected

    0 讨论(0)
  • 2021-02-18 14:05
    //Another option
    
    var selected = [];
    
    $('select :has(:selected)').each( function(){
    
        var $this = $(this);
        selected.push( { text: $this.text(), value: $this.val() );
    
    });
    
    return selected;
    
    0 讨论(0)
  • 2021-02-18 14:07

    This function will return an array of text/value pairs for the selects matching the given class.

    function getSelects(klass) {
        var selected = [];
        $('select.' + klass).children('option:selected').each( function() {
            var $this = $(this);
            selected.push( { text: $this.text(), value: $this.val() } );
        });
        return selected;
    }
    
    0 讨论(0)
  • 2021-02-18 14:09

    If all of your select boxes start with a similar id ("select_1", "select_2", "select_3", etc), you can just do:

    var arr = [];
    $("select[id^='select_']").children('option:selected').each(function(){
      //you will do this once for every selected item...
    }
    

    This allows you to loop through only specific select boxes, in case you have multiple groupings.

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