Combine change and onload events

前端 未结 4 629
长发绾君心
长发绾君心 2021-01-26 23:24

I have coded this where I add / delete classes when you select from the form. However if i choose as default select the 2nd select e.g.

4条回答
  •  旧巷少年郎
    2021-01-27 00:05

    You can export logic to a function and call this function on both change and document.ready event.

    Also, if you have to add/remove classes, try to use .toggleClass

    Sample

    $('#destination').change(function() {
      updateUIState();
    });
    
    $(document).ready(function() {
      updateUIState();
    })
    
    function updateUIState() {
      var dest = $('#destination').find(":selected").text();
      var isDest2 = dest === 'destination2';
      $('#destin').toggleClass("has-warning", isDest2);
      $('#destin').toggleClass("has-success", isDest2);
    }
    
    
    
    
    

提交回复
热议问题