简体   繁体   中英

Javascript/JQuery creating an array from multiple inputs and then checking them against other arrays

I have a form with a bunch of inputs, including cities. Other inputs either need to be shown or hidden depending on the cities the user has selected.

I have two arrays:

var biking_cities = ['newyork',];
var cars_cities = ['newyork','newjersey','metronorth','longisland','boston','chicago','sanfrancisco','london','paris','washington',];

So if any of the cities = newyork, then the biking input needs to be hidden. Same for "cars".

The city inputs all look like this:

<input class="city" type="hidden" name="city1" value="foo">
<input class="city" type="hidden" name="city2" value="foo">

And so on (max 9 cities).

What's an efficient way to create an array and check it against other arrays and then do something in case they match?

Thanks, Brian

I would actually take a slightly different approach, and use a basic JavaScript object:

var cities = {
  newyork : { bikes: false, cars: true} 
  newjersey : { bikes: true, cars: true }
  // etc
};

You can then access the data as such:

if(cities.newyork.bikes){}
if(cities.newyork.cars){}

Or, in a loop:

for(var cityName in cities){
   if(cities[cityName].bikes){ }
   if(cities[cityName].bikes){ }
}

As for hiding or showing the inputs, hard to say, given your limited example. But hiding/showing with jQuery, is as follows

<input class="city bikes" type="hidden" name="city1" value="foo">
<input class="city cars" type="hidden" name="city1" value="foo">

And the JS:

$('city.bikes').hide();
$('city.cars').show();

Check each city input and hide the appropriate elements:

$("input.city").each(function() {
    if (biking_cities.indexOf($(this).val()) != -1) hide_biking_input();
    if (cars_cities.indexOf($(this).val()) != -1) hide_cars_input();
});

Where hide_biking_input and hide_cars_input hide the inputs that I assume are elsewhere in your code.

The result is that if any of the class=city hidden inputs you have contains an element in biking_cities , the biking input gets hidden and similarly for cars_cities .

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