Skip to content
Advertisement

How to make an input required based on the value of another input?

I have two HTML form fields in my application, one displays a dropdown for users to select if they are over 18 and the second field is for parent’s name.

I want to make the parent_name field required only if the user is under 18. Here’s my current code for the appropriate form parts.

JavaScript

I’ve created the following function so far, but I’m unable to understand how to use it.

JavaScript

Update:

How to achieve the same result if the first input is of type date? So, now the second input is required only if the age provided in the first input is less than 18.

Advertisement

Answer

You can update the required attribute of the parent_name input every time the over_18 selection changes.

Few notes:

  • type="parent_name" is invalid, it should be type="text".
  • I think you’ve added multiple on select by mistake, it doesn’t make any sense here.
  • I’ve also made the initial option for select to be Select Age with value="", so now you don’t need required on parent_name in your HTML.

JavaScript
JavaScript

Update based on OP’s comment:

If age is a date input:

  • Calculate if the age is above 18 by comparing the year, month and date of the provided date with the current date.
  • Then, toggle the required attribute accordingly.

JavaScript
JavaScript
Advertisement