Robert Crous
Robert Crous

Reputation: 341

Populating a jquery array from values of a select using each

I'm trying to populate an array in Jquery with selected values from a select.

Here is my jquery (no ajax call because I first want to make the array before i call ajax to input fields into db)

$('#add-group-form').submit(function(e) {
    e.preventDefault();
    var contactsArr = [];
    $("select option").each(function(i, val){
        var $val = $(val);
        if($(i).attr('selected', 'selected')){
        contactsArr.push({value: $val.val()});
        }
    });
    console.log(contactsArr);
});

Now in all honesty i got the each from a different source.

Not sure how i check the attribute to make sure it is selected.

Thanks in advance for the help

**EDIT:

Okay so I may have forgotten to check for answers as I got distracted by trying to figure it out

This is how I've done it (tested and works in my system).

var contactsArr = [];
$(".edit-contact-select option:selected").each(function() {
    contactsArr.push({value: $(this).val()});
});

I was over-complicating the entire thing.

Upvotes: 1

Views: 1137

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Looks like you have a multiple select if so you can use .val() to get the selected values in an array

$('#add-group-form').submit(function (e) {
    e.preventDefault();
    var contactsArr = $("select").val();
    console.log(contactsArr);
});

If you want to store the selected values from multiple select elements, then use .map() like

$('#add-group-form').submit(function (e) {
    e.preventDefault();
    var contactsArr = $("select").map(function (i, val) {
        return $(this).val()
    }).get();
    console.log(contactsArr);
});

Upvotes: 1

geevee
geevee

Reputation: 5451

you don't need to iterate through options for the "selected" one. use this instead:

$('#add-group-form').submit(function(e) {
    e.preventDefault();
    var contactsArr = [];
    $('select').each(function(){
        contactsArr.push({value: $(this).val()});
    });
    console.log(contactsArr);
});

$('select').val() actually returns the SELECTED value of the select input.

hope that helps.

Upvotes: 3

Related Questions