You are viewing limited content. For full access, please sign in.

Discussion

Discussion

How can I make a multi-line field required is any radio buttons are selected No?

posted on September 14

I have a section of Yes, No, N/A questions (class= preop).  I want the multi-line Comment field (class= comment) to become required if any on the questions are checked No.  I have the following script I found on LF Answers and modified, but it works when one questions is marked No and then removes the required field whenever another question is marked Yes or N/A. In addition, it adds an asterisk every time No is selected which when more than one No is selected looks weird.  Can anyone help me properly modify this script?  I am new to JavaScript.

 

$(document).ready(function () {

    $('.preop input').change(function () {

        if ($(this).val() == 'No'){

            $('.comment label').append('<span class="cf-required">*</span>');

            $('.comment textarea').attr('required', 'True');


        } else {

            $('.comment span.cf-required').remove();

            $('.comment textarea').removeClass('required').removeAttr('required');  

        }

    })

});

0 0
replied on September 14 Show version history

You could nest a secondary if condition inside the first one to check if the required attribute is already added after verifying that it is needed.

$(document).ready(function () {

    $('.preop input').change(function () {

        if ($(this).val() == 'No'){
            
            var field = $('.comment textarea');
            
            if(!field.hasAttr('required')){
                
                $('.comment label').append('<span class="cf-required">*</span>');

                field.attr('required', 'True');

            }
        } else {

            $('.comment span.cf-required').remove();

            $('.comment textarea').removeClass('required').removeAttr('required');  

        }

    })

});

I haven't tested this so I can't guarantee it will work as-is, but the main goal was to demonstrate what I mean by a secondary condition.

Note that the second if has to be nested within the first so the required attribute doesn't get removed unexpectedly when it's already in place.

1 0
You are not allowed to follow up in this post.

Sign in to reply to this post.