1

I have some jQuery with JSON - there is one line that selects the proper state in a SELECT element - here is the line:

if (data.state) $('#state').val(data.state);

If works fine for the options like this:

<option value='NJ'>NJ</option>
<option value='PA'>PA</option>

data.state always will equal the text, like "PA" or "NJ" - but I've needed to change my options to this:

<option value='17'>NJ</option>
<option value='27'>PA</option>

So (data.state) $('#state').val(data.state); no longer works...

I'm wondering if I can change this line to somehow select the option by the TEXT, not the value...

Any thoughts? Thank you in advance PS - I did try to figure this out reading other similar requests on StackOverflow - but I'm just lost at this point....jQuery is kind of new to me.

isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

0
$("#state option").each(function() {
    if ($(this).text() == data.state) {
       $('#state').val($(this).val());
       return;
    }
});

It loops each option until it finds matching text then sets the value.

**untested

Jacob Roberts
  • 1,725
  • 3
  • 16
  • 24