views:

158

answers:

3

I'm trying to scale this but I'm a little green when it comes to creating JS functions. I managed to get this far on my own, but alas...

When a span gets a value of whatever (in this case, a city name), I want the select box to automatically match it. And I want to scale this by getting rid of all these else if's.

$(document).ready(function() {
  $('select#field1 option').removeAttr('selected');
  var whereEvent = $('span#field2').html();
  if (whereEvent == 'New York') {
    $('select#field1 option[value=New York]').attr('selected', 'true');
  } else if (whereEvent == 'Los Angeles') {
    $('select#field1 option[value=Los Angeles]').attr('selected', 'true');
  } else if (whereEvent == 'Tokyo') {
    $('select#field1 option[value=Tokyo]').attr('selected', 'true');
  } else if (whereEvent == 'London') {
    $('select#field1 option[value=London]').attr('selected', 'true');
  } else if (whereEvent == 'Sydney') {
    $('select#field1 option[value=Sydney]').attr('selected', 'true');
  } else if (whereEvent == 'Paris') {
    $('select#field1 option[value=Paris]').attr('selected', 'true');
  }
});

Can someone help me out here? I promise I'll be grateful for your help. Thank you.

+3  A: 

Maybe:

$('select#field1 option').removeAttr('selected');
var whereEvent = $('span#field2').html();
$('select#field1 option[value='+whereEvent+']').attr('selected', 'true');

?

Ionut Staicu
That's where I was confused. 'if' isn't necessary here. Thank you!
A: 

I don't know jQuery, so there's probably a more elegant way, but:

var whereEvent = $('span#field2').html();
$('select#field1 option[value=' + whereEvent + ']').attr('selected', 'true');
Andy Hume
+4  A: 

This is an option:

    $(document).ready(function() {
      $('select#field1 option').removeAttr('selected');
      var whereEvent = $('span#field2').html();
      var filter = 'select#field1 option[value=' + whereEvent + ']';
      $(filter).attr('selected', 'true');
   }

Or you could do:

    $(document).ready(function() {
      var filter = $('span#field2').html();
      $('select#field1 option').each(function(){
           this.selected = (this.value == filter);
      });
   }
Jaime Febres
This works, too. Thank you.
You also don't need to removeAttr, setting one option selected unselects the previously-selected one.
bobince