0

I have a radio button that only shows up when certain values are chosen above so in some cases the radio button wont have a checked value so I cant put a required data annotation to the model. Is there any way to make a radio button required only when the question shows up.

2
  • 1
    I'm not sure if you'd need this at all. Once selected, user can't deselect a radio button in any way. Commented May 5, 2020 at 5:26
  • You need conditional validation Commented May 5, 2020 at 6:47

1 Answer 1

1

You can create an error div class, and check if no radio check append your error message as

$('#Next').click(function(){
            if ($("[name='myoptions']:checked").length == 0){
                $('.error').text("Radio is required.");
                return false;
            }
 });

 $(document).ready(function () {
        $('#Next').click(function(){
            if ($("[name='myoptions']:checked").length == 0){
                $('.error').text("Radio is required.");
                return false;
            }
        });
    });
.radio{
margin-right: 10px;
}

.error{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="radio" name="myoptions" value="red">Radio 1<br /> 
 <input type="radio" name="myoptions" value="green">Radio 2</div>                                                    
<div class='error'></div>    

<input class="btn btn-primary" type="submit" value="Next" id="Next"/>

<script>
   
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.