Set Field Disabled Based on Selected Option On Load Then On Change Jquery

I have some jquery that fires when I choose another option in a select like this:

$(document).ready(function() {
  $("[name=msgType]").change(function(){
   if ($("#text").is(':selected')) { // TYPE TEXT
      $("#msgBody").removeAttr('disabled');
      $("#msgTitle").attr("disabled", "disabled");       
      $("#msgText").attr("disabled", "disabled");
      $("#msgUrl").attr("disabled", "disabled");  
      $("#msgPicUrl").attr("disabled", "disabled"); 
      $("#msgVideoUrl").attr("disabled", "disabled");

   } else if ($("#link").is(':selected')) { // TYPE LINK
      $("#msgBody").attr("disabled", "disabled"); 
      $("#msgTitle").removeAttr('disabled');       
      $("#msgText").removeAttr('disabled');
      $("#msgUrl").removeAttr('disabled'); 
      $("#msgPicUrl").removeAttr('disabled');
      $("#msgVideoUrl").attr("disabled", "disabled");  
   } 
 });
});

This works fine. However, when I initially load the page, I set the option in the select, but that obviously does not cause the "change" function to occur, so the corresponding disabled fields are not disabled until I manually change the dropdown.

How can I also set all the disabled fields for the corresponding select option when I initially load the page, but also when I change the dropdown again?

Answers 1

  •   $("[name=msgType]").change(function(){
       if ($("#text").is(':selected')) { // TYPE TEXT
          $("#msgBody").removeAttr('disabled');
          $("#msgTitle").attr("disabled", "disabled");       
          $("#msgText").attr("disabled", "disabled");
          $("#msgUrl").attr("disabled", "disabled");  
          $("#msgPicUrl").attr("disabled", "disabled"); 
          $("#msgVideoUrl").attr("disabled", "disabled");
    
       } else if ($("#link").is(':selected')) { // TYPE LINK
          $("#msgBody").attr("disabled", "disabled"); 
          $("#msgTitle").removeAttr('disabled');       
          $("#msgText").removeAttr('disabled');
          $("#msgUrl").removeAttr('disabled'); 
          $("#msgPicUrl").removeAttr('disabled');
          $("#msgVideoUrl").attr("disabled", "disabled");  
       } 
     }).change();//call change event manually on load
    

    To call the change event on load you have to manually call .change()


Related Articles