0

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

3
  • It's hard to see what your trying to achieve here, can you provide some code on jsfiddle.net Commented Jun 3, 2011 at 14:30
  • How can the user select cities with type='hidden'? Commented Jun 3, 2011 at 14:32
  • @andrew im mimicking a selectbox with a UL and setting the value of the input on an li click Commented Jun 3, 2011 at 14:35

2 Answers 2

1

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();
1
  • Hi Matt. Thanks! This is a great approach. Commented Jun 3, 2011 at 15:15
0

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

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.