mardi 24 mars 2015

Caching variables for events without making them global


You can say that this would apply to most events but in my case the change event for select boxes. I have two select boxes. I want to insert/re-insert depending the options from the select box depending on which option is selected within the first select box. I've managed to do this but with the caveat of making a global variable for the options I want to manipulate. Is there a way to do this within the event or some sort've workaround where the variable isn't global?


HTML



<select id="vehicles">
<option value="motorcycle">Motorcycle</option>
<option value="bicycle">Bicycle</option>
<option value="unicycle">Unicycle</option>
</select>
<select id="speeds">
<option class="remove" value="four">Four Speed</option>
<option class="remove" value="three">Three Speed</option>
<option class="remove" value="two">Two Speed</option>
<option value="one">One Speed</option>
</select>


JS



$(function() {
var options = $(".remove");

$("#vehicles").on("change", function() {
if ($("option:selected").attr("value") == "unicycle") {
options.detach();
} else {
$("#speeds").append(options)
}
});
});


JSFiddle





Aucun commentaire:

Enregistrer un commentaire