We have a select box for entering a position title. The select box, powered by Select2 4.0.13 (which is a great library but the documentation really sucks), “auto-suggests” from existing titles (to encourage consistency). However, there are also have times where they are editing someone’s existing title and our users have long requested that the box pre-fill in said title so it’s easier to make minor changes without having to retype the whole thing, which also increases the likelihood of adding spelling errors. This can be especially useful when someone got a promotion from a level I position to a level II or the like, which is a fairly common title schema in our organization.
Since we’re doing a ton of updates to this app anyway, figured I’d look that up, thinking it would be a “quick” fix 🤣 Lots of searching found answers totally different than what I needed or answers from 2013 which seemed to result may be a configuration option that maybe got removed later (it was confusing)? Anyway, hours later, I finally found the solution, which ended up being relatively easy and works for both the new and modify forms, so here it is in case anyone else has been hunting for this. 🙂
First, the select box, with obviously a selection of titles because otherwise, this page would be ridiculously huge LOL
<div class="form-group row"> <label class="col-sm-2 required" for="position_title">Position Title:</label> <div class="col-sm-9"> <select name="position_title" id="position_title" class="form-control" required="required"><option value=""></option> <option value="4-H & FCS Assistant">4-H & FCS Assistant</option> <option value="4-H Assistant">4-H Assistant</option> <option value="4-H Coordinator/Secretary">4-H Coordinator/Secretary</option> <option value="4-H Curriculum Enrichment Program Assistant">4-H Curriculum Enrichment Program Assistant</option> <option value="4-H Program Assistant">4-H Program Assistant</option> <option value="4-H Program Coordinator">4-H Program Coordinator</option> <option value="4-H Secretary">4-H Secretary</option> </select> </div> </div>
Then the JavaScript; if you want this change to be universal to all your select boxes, everything except the actual select2 initialization could be moved to your site JS, though you may need to tweak if to only apply to Select2s that have tags enabled.
$(document).ready(function() { $('#position_title').select2({ tags: true, placeholder: 'Enter position title; as you type, suggested titles will be displayed to choose from', allowClear: true }); var prevselection = ''; $('select').on('select2:opening', function(event){ prevselection = $(event.target).find(':selected').val(); }); $('select').on('select2:open', function(event){ $('.select2-search__field').val(prevselection); }); });