1

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.

1
  • if($(i).attr('selected', 'selected')){ is the problem. you don't need to assign "selected" to the "selected" attribute. you need to find out whether it is "selected" or not. Commented Nov 25, 2014 at 7:12

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, the $('select').each(function(args){}) args were off (this answer fixed it), and the $(i) was wrong, should be $(this) (again, GalV's answer fixed it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.