Search code examples
jquerydatatablescoldfusion

jQuery Loop Through Data in Select Statement and Have Saved Option PreSelected


I have this admin page that lists a group of different cars where the administrator can come and click on an edit button and update one of the cars. When this happens the car is brought up in a form in a modal where changes can be made. The form has a save and cancel button in the modal.

Various things can be updated are typical car things like year, make, model, trim level, color, year, etc. So for example, one of the things that can be updated about the item is color, and a Select Statement with the colors offered for that model are listed. The Select is populated by a SQL Query.

The question: How do I have the vehicle color that is already saved, pre-Selected in the form element in the modal? Like the color of this particular car in the list was listed as TorRed and it should be Octane Red instead and the Administrator wants to update this particular cars color.

It's in Data Tables using jQuery, the middleware is Coldfusion, & the data is stored in a SQL Server database.

<i class="fa fa-pencil-square-o edit-button" aria-hidden="true" title="Edit Car" data-carid="#CarID#" data-carmake="#CarMake#" data-carmodel="#CarModel#" data-trimlevel="#TrimLevel# data-year="#Year#" data-colorname="#ColorName#" data-colorid="#ColorID#" data-isactive="#isActive#"></i>


$(document).ready(function(){
        $(document).on('hidden.bs.modal', '.modal', function () {
            $(this).removeData('bs.modal');
            const modalForm = document.querySelector('#ModalForm');
            $('#CarID').val('');
            modalForm.reset();                
        });
        loadData();

        $(document).on('shown.bs.modal', '.modal', function () {
            $('#CarMake').focus();
        })

        $('#data_grid_display').on('click', '.edit-button', function(e) {
            e.preventDefault();
            const ColorID = $(this).data('colorid');
            const ColorName = $(this).data('colorname');
            const isActive = $(this).data('isactive');
            $('#ColorID').val(ColorID);
            $('#ColorName').val(ColorName);
            const isActiveChecked = isActive ? true : false;
            $('#isActive').prop('checked',isActiveChecked);
            $('#TheModal').modal('show');
        });


//The Select statement in the form on the modal
<cfoutput>
<select name="ColorID" class="frmcontrol" placeholder="Car Color">
   <option value="" Selected>--- Select ---</option>
   <cfloop query="GetColors">
      <option value="#ColorID#">#ColorName#</option>
   </cfloop>    
</select>
</cfoutput>

Solution

  • I got help at work to figure it out. This is all the jQuery I needed.

    $('#ColorID > option').each(function() {
      if ($(this).val() == ColorID) {
        $(this).attr("selected", "selected");
      }
    });