Created
August 5, 2011 12:07
-
-
Save brenes/1127395 to your computer and use it in GitHub Desktop.
Script used to link two selects acording to some options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Select Linker: This extension links two selects so the options loaded depends on each select. | |
How to use it: | |
> options = {"__default" : ...} | |
> $("#select_one").link_select("#select_two", options, false); | |
Params: | |
* other_select : Selector to reach other select | |
* options: a hash of options with the following format | |
{ "value of this select" : { "values": | |
[ | |
{ "label" : "Label for the option 1", "value" : "Value for the option 1" }, | |
{ "label" : "Label for the option 2", "value" : "Value for the option 2" }, | |
... | |
], | |
... | |
,"__default" : { "values": | |
[ | |
{ "label" : "Label for the option 1", "value" : "Value for the option 1" }, | |
{ "label" : "Label for the option 2", "value" : "Value for the option 2" }, | |
... | |
] | |
} | |
"__default" key set the default options for the linked select | |
* mutual: If the relationship is mutual we must change the behaviour a little bit. | |
NOTE: Working with mutual links is a little bit weird (and nasty right now). | |
We must call the function on both selects, passing the apropiate options for each functions. | |
I mean it's not as simple as: | |
> options = {"__default" : ...} | |
> $("#select_one").link_select("#select_two", options, true); | |
But | |
> options_1 = {"__default" : ...} | |
> options_2 = {"__default" : ...} // Not are different hashes | |
> $("#select_one").link_select("#select_two", options_1, true); | |
> $("#select_two").link_select("#select_one", options_2, true); | |
*/ | |
$.fn.link_select = function(other_select, options, mutual) | |
{ | |
$(this).change(function(e) { | |
if (mutual && $(other_select).hasClass("main_selector")) | |
{ | |
return false; | |
} | |
$(other_select).empty(); | |
option = options[$(this).val()] | |
if (!option) | |
{ | |
option = options["__default"] | |
} | |
selected = true; | |
for (value in option["values"]) | |
{ | |
value = option["values"][value] | |
$(other_select).append("<option value='"+value.value+"' "+(selected ? "selected=selected" : "")+">"+value.label+"</option>") | |
selected = false; | |
} | |
$(other_select).parent().children("span").text(option["values"][0].label); | |
if (mutual) | |
{ | |
if ($(this).val().value == "") | |
{ | |
$(this).removeClass("main_selector"); | |
} | |
else | |
{ | |
$(this).addClass("main_selector"); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment