Sha256: 90ed5df8c7c5ca1cff407def4abd7489ff49c1a01be97ef1f4fdce1fbc41b4a9

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

var SubdivisionSelect = (function() {
  function SubdivisionSelect(element) {
    this._countrySelect = element;
    this._subdivisionSelect = $(element).
      closest("form").
      find(SubdivisionSelect.subdivisionSelector);
  };

  SubdivisionSelect.subdivisionSelector = "select.subdivision-selector";
  SubdivisionSelect.countrySelector = "select[id$=country]";

  SubdivisionSelect.init = function () {
    var klass = this;

    return $(klass.countrySelector).each(function() {
      return new klass(this).init();
    });
  };

  SubdivisionSelect.prototype.init = function() {
    var self = this;

    $(this._countrySelect).change(function() {
      $.ajax( {
        url: "/subdivisions",
        data: { country_code: $(this).val() }
      }).success(function(newSubdivisions) {
        self._clearSubdivisionSelect();
        self._updateSubdivisionSelect(newSubdivisions);
      });
    });
  };

  SubdivisionSelect.prototype._updateSubdivisionSelect = function(newSubdivisions) {
    var self = this;
    var isEmpty = $.isEmptyObject(newSubdivisions);

    $.each(newSubdivisions, function(alpha2, name) {
      self._subdivisionSelect.append($("<option></option>").attr("value", alpha2).text(name));
    });

    // Disable the select if there are no newSubdivisions (and un-do that once there are some)
    self._subdivisionSelect.prop("disabled", isEmpty);

    // If there are none, make it say "none"
    if (isEmpty) {
      self._subdivisionSelect.append($("<option></option>").text("none"));
    }
  };

  // Not only empty the select, but:
  // if the first element is blank, add a blank element before all others
  SubdivisionSelect.prototype._clearSubdivisionSelect = function() {
    var includeBlank = this._subdivisionSelect.children().first().text() === "";

    this._subdivisionSelect.empty();

    if (includeBlank) {
      this._subdivisionSelect.append($("<option></option>"));
    }
  };

  return SubdivisionSelect;
})();

$(function() {
  SubdivisionSelect.init();
});

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
subdivision_select-0.0.2 app/assets/javascripts/subdivision_select.js
subdivision_select-0.0.1 app/assets/javascripts/subdivision_select.js