I have run into a problem and would appreciate help devising a creative, and lightweight approach around it. I need to show descriptive text every time user selects on option from a select list. I would use something like:

jQuery

$('#machines').change(function() {
  var $selected = $(this).find(':selected');
  $('#description').html($selected.data('description'));
}).trigger('change');
<div class="form-group">
  <label for="machines">Machines</label>
  <select id="machines" class="form-control">
    <option data-description="Printer">Printer</option>
    <option data-description="Copy">Copy</option>
    <option data-description="Scanner">Scanner</option>
  </select>
</div>
<div class="form-group">
  <span id="description"></span>
</div>


<script src="js/jquery-3.3.1.slim.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>

<script type="text-javascript">
    $('#machines').change(function() {
        var $selected = $(this).find(':selected');
        $('#description').html($selected.data('description'));
    }).trigger('change');
</script>

1 Answers

0
Assilli Taher On Best Solutions

May be the function is executed before the document is ready. Try to use document.ready function like this:

$( document ).ready(function() {
    $('#machines').change(function() {
        var $selected = $(this).find(':selected');
        $('#description').html($selected.data('description'));
    }).trigger('change');
});