JSFiddle: https://jsfiddle.net/4gr0kdyj/
In jQuery 2.x I need to save and restore the selection state of a Multi-Select box. In between, I need to Select All options. The provided JSFiddle is too verbose and also it doesn't work, there's a bug somewhere. I'm just wondering, is there a simpler way?
Possible outcomes of the Save/Restore are
- No selection
- Some selection(s)
Strategy (too long)
// 1. backup state
var sels = $('select[name="advocateSearchParams.answerMap[11].answerIdList"]').val();
// 2. temporarily select all
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').prop('selected', true);
// 3. restore state
if (sels != null) {
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').each(function(index, element) {
if ($.inArray($(element).attr('value'), sels)) {
$(element).prop('selected', true);
} else {
$(element).prop('selected', false);
}
});
} else {
// all deselected
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').prop('selected', false);
}
$('#deselectAll').click(function() {
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').prop('selected', false);
});
$('#backupRestore').click(function() {
// 1. backup state
var sels = $('select[name="advocateSearchParams.answerMap[11].answerIdList"]').val();
alert('sels: ' + sels);
// 2. temporarily select all
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').prop('selected', true);
alert('selected all');
// 3. restore state
if (sels != null) {
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').each(function(index, element) {
if ($.inArray($(element).attr('value'), sels)) {
$(element).prop('selected', true);
} else {
$(element).prop('selected', false);
}
});
} else {
// all deselected
$('select[name="advocateSearchParams.answerMap[11].answerIdList"] option').prop('selected', false);
alert('All deselected');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="advocateSearchParams.answerMap[11].answerIdList" size="10" multiple="multiple">
<option value="103">Type1</option>
<option value="104">Type2</option>
<option value="105">Type3</option>
<option value="106">Type4</option>
<option value="107">Type5</option>
<option value="108">Type6</option>
</select>
<button id="backupRestore">
Backup/Restore
</button>
<button id="deselectAll">
Deselect All
</button>