Zapnologica
Zapnologica

Reputation: 22556

get all options in a select element with jQuery not working

I am trying to get a list of strings with all the values of the

Here is my html:

  <label>Select Roles</label>
    <span id="dualselect" class="dualselect">
        <select name="RolesSelect" id="dualSelectRoles1" multiple="multiple" size="10">
            <option value="">Avaliable Roles</option>
        </select>

        <span class="ds_arrow">
            <span class="arrow ds_prev">&laquo;</span>
            <span class="arrow ds_next">&raquo;</span>
        </span>

        <select name="select4" multiple="multiple" id="dualSelectRoles2" size="10">
            <option value="12">Users Roles</option>
        </select>
    </span>

Here is my JS:

   <script>
function submitForm() {
    var arr = new Array;
    $("#dualSelectRoles2").each(function () {
        arr.push($(this).val());
    });
    alert(arr);
}
</script>

My alert is displaying nothing?

Upvotes: 0

Views: 49

Answers (4)

James Hibbard
James Hibbard

Reputation: 17755

You need to reference the option elements, then iterate over them:

var arr = new Array;
$("#dualSelectRoles2 option").each(function () {
    arr.push(this.value);
});
alert(arr);

Also, you can replace $(this).val() with this.value. You don't need a jQuery object here.

fiddle

Upvotes: 1

Awlad Liton
Awlad Liton

Reputation: 9351

DEMO : http://jsfiddle.net/qsDn5/22/

you need to run loop through each option.

 var arr = new Array;
    $("#dualSelectRoles2 option").each(function () {
        arr.push(this.value);
    });
    alert(arr);

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

It should be:

  var arr = new Array;
$("#dualSelectRoles2 option").each(function () {
    arr.push($(this).val());
      alert(arr);
});

Fiddle

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to find the option elements within the select, then use .map()

function submitForm() {
    var arr = $("#dualSelectRoles2 option").map(function () {
        return this.value
    }).get();
    alert(arr);
}

Upvotes: 0

Related Questions