SO-76808869
by David Thomas
HTML
<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();
// we're using this element in two places in this example, so
// it makes sense to cache it in a variable:
let selectElement = document.querySelector('#type');
selectElement
// binding the anonymous function of the
// EventTarget.addEventListener() method:
.addEventListener('change', (evt) => {
// using destructuring assignment to retrieve
// the currentTarget property, and rename it
// to the variable 'el':
let {
currentTarget: el
} = evt,
// retrieving the selected value of the
// element, again: trimming away white-space
// from beginning and end, and converting
// to lower-case:
{
form
} = el,
value = el.value.trim().toLowerCase();
// using Element.querySelectorAll() to find all
// matching elements contained within the <form>
// element that contains the <select>:
form.querySelectorAll('label')
// iterating over the NodeList returned:
.forEach(
(label) => {
// this is because while jQuery guards against the
// consequence of a selector returning null,
// JavaScript doesn't; so here we first retrieve
// the <input>:
let input = label.querySelector('input');
// and here we test for its existence (because obviously
// the <label> prior to the <select> has no <input> element):
if (input) {
// here we do exactly as we did in jQuery, we update
// the disabled property of the <input> element depending
// on the presence or absence of the 'value' in the
// <label> element's text:
label.querySelector('input').disabled = !label.textContent.toLowerCase().includes(value)
}
})
});
// firing the 'change' event after the event-listener is bound, using
// EventTarget.dispatchEvent, in order that the <input> elements are
// in the correct state on page-load:
selectElement.dispatchEvent(new...