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.
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.