I want to temporarily disable lname textbox because the fname is empty, but if the fname is not empty the lname is enabled. I have a code but I don’t think it is correct or wrong, you can visit my code here https://jsfiddle.net/Jayme207/ejks5xqL/12/
const fname = document.querySelector(".fname");
const lname = document.querySelector(".lname");
lname.readonly = true;
fname.addEventListener("keyup", () => {
if (fname.value.length > 0) {
lname.readonly = false;
} else {
lname.readonly = true;
}
})
<form action="/action_page.php">
<label for="fname">Fname:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Lname:</label>
<input type="text" id="lname" name="lname" disabled><br><br>
<input type="submit" value="Submit">
</form>
4
Answers
We should select using
#fname
since, we are having the ID field asfname
, the selector you used is for classes. We can go for the more specificgetElementById
to fetch the element by ID.We can use
setAttribute
andremoveAttribute
to toggle the disabled condition.A short solution, using event delegation (note: enables last name field when first name field value length >= 3).
As already said, you need to use the ID selector or getElementById.
Here is a much simpler version