开发者

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

开发者 https://www.devze.com 2023-03-10 17:53 出处:网络
I have a form with a bunch of inputs, including cities. Other input开发者_高级运维s either need to be shown or hidden depending on the cities the user has selected.

I have a form with a bunch of inputs, including cities. Other input开发者_高级运维s 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消