jQuery.SimpleSelect demo #3
Updating the select's options on the fly, and updating the SimpleSelect accordingly
HTML
<script src="http://pioul.fr/ext/jquery-simpleselect/jquery.simpleselect.2.0.0.min.js"></script>
<link rel="stylesheet" href="http://pioul.fr/ext/jquery-simpleselect/jquery.simpleselect.2.0.0.min.css">
<div>
<label for="example-select">What's your favorite cat breed?</label>
<select id="example-select">
<option>Persian</option>
<option>Maine Coon</option>
<option>Exotic</option>
<option>Siamese</option>
<option>Abyssinian</option>
<option>Ragdoll</option>
<option>Birman</option>
<option>American Shorthair</option>
<option>Oriental</option>
<option>Sphynx</option>
</select>
</div>
<div>
<form id="add-option-form">
<label for="add-option">Add an option to the select, then open it</label>
<input type="text" id="add-option" value="Burmese"/>
<input type="checkbox" id="should-select-option"/>
<label for="should-select-option">The new option should be selected</label>
<input value="ok" type="submit"/>
</form>
</div>
CSS
body {
padding: 10px;
margin: 0;
background: #fff;
font: 14px Arial, Helvetica, Geneva, sans-serif;
line-height: 1.5em;
color: #3a3a3a;
}
body > div {
float: left;
margin: 40px 40px 0 0;
}
input[type="text"] {
height: 18px;
padding: 9px 10px;
border: 1px solid #ddd;
line-height: 18px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
input[type="submit"] {
visibility: visible;
}
label {
display: block;
}
label[for="should-select-option"] {
display: inline;
}
JavaScript
var select = $("#example-select").simpleselect(),
newOptionInput = $("#add-option"),
newOptionAutoSelectionCheckbox = $("#should-select-option"),
newOption;
$("#add-option-form").on("submit", function(e) {
e.preventDefault();
newOption = $("<option>").text(newOptionInput.val());
if (newOptionAutoSelectionCheckbox.prop("checked")) newOption.prop("selected", true);
select
.append(newOption)
.simpleselect("refreshContents")
.simpleselect("setActive");
});