How to fetch all the option values(selected/unsele

2019-04-26 14:29发布

I want to fetch all the option values(selected/unselected) in a selectbox on click of a button. How can I do this?

3条回答
\"骚年 ilove
2楼-- · 2019-04-26 15:02
var arr = new Array;

    $("#selectboxid option").each  ( function() {
       arr.push ( $(this).val() );
    });

alert ( arr.join(',' ) );

in the button click

    $("#btn1").click ( function() {
        var arr = new Array;
        $("#selectboxid option").each ( function() {
            arr.push ( $(this).val() );
        });
        alert ( arr );
    });
查看更多
Deceive 欺骗
3楼-- · 2019-04-26 15:14

I think is a good opportunity to use the Traversing/map method:

var valuesArray = $("#selectId option").map(function(){
  return this.value;
}).get();

And if you want to get two separate arrays containing the selected and unselected values you can do something like this:

var values = {
  selected: [],
  unselected:[]
};

$("#selectId option").each(function(){
  values[this.selected ? 'selected' : 'unselected'].push(this.value);
});

After that, the values.selected and values.unselected arrays will contain the right elements.

查看更多
Animai°情兽
4楼-- · 2019-04-26 15:23

err ok ..

$('#selectbox').click(function() {
  var allvals = [];
  $(this).find('option').each(function() { allvals.push( $(this).val() ); };
});

or maybe you mean

$('#thebutton').click(function() {
  var allvals = [];
  $('#theselectbox').find('option').each(function() { allvals.push( $(this).val() ); };
});
查看更多
登录 后发表回答