[9240] | 1 | /*
|
---|
| 2 | * Chained - jQuery non AJAX(J) chained selects plugin
|
---|
| 3 | *
|
---|
| 4 | * Copyright (c) 2010 Mika Tuupola
|
---|
| 5 | *
|
---|
| 6 | * Licensed under the MIT license:
|
---|
| 7 | * http://www.opensource.org/licenses/mit-license.php
|
---|
| 8 | *
|
---|
| 9 | */
|
---|
| 10 |
|
---|
| 11 | (function($) {
|
---|
| 12 |
|
---|
| 13 | $.fn.chained = function(parent_selector, options) {
|
---|
| 14 |
|
---|
| 15 | return this.each(function() {
|
---|
| 16 |
|
---|
| 17 | /* Save this to self because this changes when scope changes. */
|
---|
| 18 | var self = this;
|
---|
| 19 | var backup = $(self).clone();
|
---|
| 20 |
|
---|
| 21 | /* Handles maximum two parents now. */
|
---|
| 22 | $(parent_selector).each(function() {
|
---|
| 23 |
|
---|
| 24 | $(this).bind("change", function() {
|
---|
| 25 | $(self).html(backup.html());
|
---|
| 26 |
|
---|
| 27 | /* If multiple parents build classname like foo\bar. */
|
---|
| 28 | var selected = "";
|
---|
| 29 | $(parent_selector).each(function() {
|
---|
| 30 | selected += "\\" + $(":selected", this).val();
|
---|
| 31 | });
|
---|
| 32 | selected = selected.substr(1);
|
---|
| 33 |
|
---|
| 34 | /* Also check for first parent without subclassing. */
|
---|
| 35 | /* TODO: This should be dynamic and check for each parent */
|
---|
| 36 | /* without subclassing. */
|
---|
| 37 | var first = $(parent_selector).first();
|
---|
| 38 | var selected_first = $(":selected", first).val();
|
---|
| 39 |
|
---|
| 40 | $("option", self).each(function() {
|
---|
| 41 | /* Remove unneeded items but save the default value. */
|
---|
| 42 | if (!$(this).hasClass(selected) &&
|
---|
| 43 | !$(this).hasClass(selected_first) && $(this).val() !== "") {
|
---|
| 44 | $(this).remove();
|
---|
| 45 | }
|
---|
| 46 | });
|
---|
| 47 |
|
---|
| 48 | /* If we have only the default value disable select. */
|
---|
| 49 | if (1 == $("option", self).size() && $(self).val() === "") {
|
---|
| 50 | $(self).attr("disabled", "disabled");
|
---|
| 51 | } else {
|
---|
| 52 | $(self).removeAttr("disabled");
|
---|
| 53 | }
|
---|
| 54 | $(self).trigger("change");
|
---|
| 55 | });
|
---|
| 56 |
|
---|
| 57 | /* Force IE to see something selected on first page load. */
|
---|
| 58 | $("option", this).first().attr("selected", "selected");
|
---|
| 59 |
|
---|
| 60 | /* Force updating the children. */
|
---|
| 61 | $(this).trigger("change");
|
---|
| 62 |
|
---|
| 63 | });
|
---|
| 64 | });
|
---|
| 65 | };
|
---|
| 66 |
|
---|
| 67 | /* Alias for those who like to use more English like syntax. */
|
---|
| 68 | $.fn.chainedTo = $.fn.chained;
|
---|
| 69 |
|
---|
| 70 | })(jQuery);
|
---|