Combine change and onload events

前端 未结 4 621
长发绾君心
长发绾君心 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:02

    You do it on page load. If you control where your script tags go, you just do it in immediately-run code in your script. If you don't control where script tags go, put it in a ready handler.

    Here's that first option:

    function setDestinationWarningFlags() {
      var dest = $('#destination').find(":selected").text();
    
      if (dest === 'destination1') {
        console.log('here1');
        $('#destin').removeClass("has-warning");
        $('#destin').addClass("has-success");
      } else if (dest === 'destination2') {
        console.log('here2');
        $('#destin').removeClass("has-success");
        $('#destin').addClass("has-warning");
      }
    }
    // Do it on change:
    $('#destination').change(setDestinationWarningFlags);
    // Initial setup:
    setDestinationWarningFlags();
    
    
    
    
    

    If you have to use a ready callback instead, just change the last bit from:

    // Initial setup:
    setDestinationWarningFlags();
    

    to

    // Initial setup:
    $(setDestinationWarningFlags);
    

    ...which is a shortcut for ready:

    function setDestinationWarningFlags() {
      var dest = $('#destination').find(":selected").text();
    
      if (dest === 'destination1') {
        console.log('here1');
        $('#destin').removeClass("has-warning");
        $('#destin').addClass("has-success");
    
      } else if (dest === 'destination2') {
        console.log('here2');
        $('#destin').removeClass("has-success");
        $('#destin').addClass("has-warning");
      }
    }
    // Do it on change:
    $('#destination').change(setDestinationWarningFlags);
    // Initial setup:
    $(setDestinationWarningFlags);
    
    
    
    
    

提交回复
热议问题