简体   繁体   中英

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.

you don't need to iterate through option s 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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM