SO-76808869

by David Thomas

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="">
  <label>Sub Department :</label>
  <select id="type">
    <option value="ward">Ward</option>
    <option value="room">Room</option>
  </select>
  <label> Ward No<input type="text" name="abc" id="abc"></label>
  <label> Ward Name <input type="text" name="abc1" id="abc1"></label>
  <label> Room No<input type="text" name="roomno" id="roomno"></label>
  <label> Room Name <input type="text" name="roomname" id="roomname"></label>
</form>

CSS

label {
  display: flex;
  gap: 1rem;
  inline-size: 30%;
  justify-content: end;
  padding-block: 0.25rem;
}

input {
  border: 2px solid var(--stateIndicator);
  inline-size: 10rem;
  padding-block: 0.25rem;
  padding-inline: 0.5rem;
  transition: border-color 250ms;
}

input:enabled {
  --stateIndicator: palegreen;
}

input:disabled {
  --stateIndicator: salmon;
}

JavaScript

console.clear();
// selecting the relevant element via its id, using a CSS selector, and
// using the on() method to bind the anonymous function as the event-
// handler of the 'change' event fired on the identified element:
$('#type').on('change', function() {
  // getting the currently selected value (as a string), using
  // String.prototype.trim() to remove leading and trailing white-space,
  // and then converting to lower-case text for comparison:
  let value = $(this).val().trim().toLowerCase();

  // selecing all <label> elements, and iterating over that collection
  // using each():
  $('label').each(function() {
    // $(this) is the current <label> of each iteration:
    $(this)
      // from the <label> we find the nested <input>:
      .find('input')
      // we use the prop() method to update the 'disabled' property:
      .prop('disabled',
        // and here we convert the text of the current <label> ($(this))
        // to lower-case, and use String.prototype.includes() to
        // return a Boolean; this is true if the value (the string
        // we're looking for) is included, and false if not; because
        // we're setting the disabled/"inactive" state, we invert
        // that Boolean to appropriately disable/enable the <input>:
        !$(this).text().toLowerCase().includes(value)
      );
  });
  // firing the 'change' event after the event-listener is bound so
  // that the <input> elements are in the correct state on page-load:
}).change();