LMAOman LMAOman - 11 months ago 113
jQuery Question

jQuery multiple selectors syntax

Guys is this syntax correct? I'm trying to make a

dropdown select
and get the value but I'm not sure if this syntax of multiple selectors are correct

var countries = [];
var locations = [];
var zips = [];
$.each($(".country option:selected, .location option:selected ,.zip option:selected"), function(){
countries.push($(this).val());
locations.push($(this).val());
zips.push($(this).val());
});

Answer Source

The way you are doing can be correct. You are using the jQuery.each() method. If you are targeting jQuery objects, I'd go with the .each() method. I've written a 3rd method to properly place the values into the correct array. When in doubt, please reference the jQuery API. It's packed full of information and useful examples.

/* Method 1 - jQuery.each( object, callback ) */
var countries = [];
var locations = [];
var zips      = [];
$.each($('.country option:selected, .location option:selected, .zip option:selected'), function(index, value) {
    countries.push($(this).val());
    locations.push($(this).val());
    zips.push($(this).val());
});
console.log('Method 1 - countries', countries);
console.log('Method 1 - locations', locations);
console.log('Method 1 - zips', zips);

/* Method 2 - .each( function ) */
var countries = [];
var locations = [];
var zips      = [];
$('.country option:selected, .location option:selected, .zip option:selected').each(function() {
    countries.push($(this).val());
    locations.push($(this).val());
    zips.push($(this).val());
});
console.log('Method 2 - countries', countries);
console.log('Method 2 - locations', locations);
console.log('Method 2 - zips', zips);

/* Suggested Method */
var countries = [];
var locations = [];
var zips      = [];
$('.country option:selected, .location option:selected, .zip option:selected').each(function() {
    if($(this).parents('.country').length) countries.push($(this).val());
    if($(this).parents('.location').length) locations.push($(this).val());
    if($(this).parents('.zip').length) zips.push($(this).val());
});
console.log('Suggested Method - countries', countries);
console.log('Suggested Method - locations', locations);
console.log('Suggested Method - zips', zips);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="country">
    <option>USA</option>
</select>
<select class="location">
    <option>Florida</option>
</select>
<select class="zip">
    <option>32935</option>
</select>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download