Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How to require fields if a certain radio button is checked?

How to require fields if a certain radio button is checked?

1 Answer

Hi Bhaskar,

I would use jQuery to listen for when a radio button is checked and then apply the property required to the input field you want required. There are many different ways to go about solving this. Here is how I did it:

<body>
    <form action="" method="post">
        <label for="required_later">Required if Option2 selected</label>
        <input type="text" name="text_input_field" id="required_later" disabled><br>

        <input type="radio" id="option1" name="radio_options" value="option1">
        <label for="option1">Option1</label><br>

        <input type="radio" id="option2" name="radio_options" value="option2">
        <label for="option2">Option2</label><br>
        <input type="submit" name="submit" value="Submit">
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $("#option1").click(function() {
            $("#required_later").prop("required", false);
            $("#required_later").prop("disabled", true);
        });
        $("#option2").click(function() {
            $("#required_later").prop("required", true);
            $("#required_later").prop("disabled", false);
            $("#required_later").focus();
        });
    </script>
</body>