0

I have a form for addresses and I am using Geocomplete to populate that form. I have my US states in a select who's options have values as state codes and text as state name. How can I have the return from the Geocomplete trigger make the the proper selection from 'administrative_area_level_1'?

What I have so far:

<select name="administrative_area_level_1"  class="form-control">
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
</select>

I have changed the following in geocomplete:

    // Assign a given `value` to a single `$element`.
// If the element is an input, the value is set, otherwise it updates
// the text content.
setDetail: function($element, value){

  if (value === undefined){
    value = "";
  } else if (typeof value.toUrlValue == "function"){
    value = value.toUrlValue();
    }
  alert(value);
  if ($element.is(":input")) {
      $element.val(value);
  } else if ($element.is('select')) {
      alert($element.attr('name') + ' ' + value);
      $element.children('text=' + value).attr("selected", "true");
  } else {
    $element.text(value);
  }
},

I added the part for if .is('select). It's not getting entered though. I can see with the alert outside of the if block that the state is coming back by state name and state code, but am unsure how to catch it.

Dan Wier
  • 334
  • 5
  • 16

1 Answers1

0

It's not entering that block because select is a type of input.

If your value attributes are the state abbreviations, you just have to change administrative_area_level_1 to administrative_area_level_1_short. This will actually set the value but not trigger the change. Here's how I fixed that in the plugin:

  if ($element.is(":input")) {
      $element.val(value).trigger('change');
  } else {
      $element.text(value);
  }

In our case, the values for states were numeric so I had to filter through the options in the dropdown and see if the text matched. Here's what I did to make that work:

  if ($element.is(":input")) {
      $element.val(value);
      if ($element.is("select")) {
          $('#' + $element.attr("id") + " option").filter(function () {
              return $(this).text() == value;
          }).prop('selected', true).trigger("change");
      }
  } else {
      $element.text(value);
  }