1

Programmatically selecting radio button is not hiding previously displayed validation message.

Codepen: https://codepen.io/vimalanjg/pen/QQYpyE

  $(function()
  {
    $('#myform').validate(
      {
        rules:
        {
          Color:{ required:true }
        },
        messages:
        {
          Color:
          {
            required:"Please select a Color<br/>"
          }
        },
        errorPlacement: function(error, element) 
        {
            if ( element.is(":radio") ) 
            {
                error.appendTo( element.parents('.container') );
            }
            else 
            { // This is the default behavior 
                error.insertAfter( element );
            }
         }
      });

      $('#myform').submit();

      $('input:radio[name="Color"][value="Red"]')
            .prop('checked', true)
            .trigger('change');
  });

The above code is an example to reproduce the issue.

enter image description here

In the above snapshot, even though the radio button is selected, the validation message is still displaying.

I am wondering why jquery validation is not hiding error messages when the required value is set programmatically?

Any suggestion will be greatly appreciated.

JGV
  • 5,037
  • 9
  • 50
  • 94

1 Answers1

1

"I am wondering why jquery validation is not hiding error messages when the required value is set programmatically?"

Because the plugin is setup to respond to triggers from the user... typing, clicking, navigating, etc. It's not designed to constantly monitor for changes from the programming.

When doing anything programmatically that could affect the form's validity, always attach the .valid() method in order to programmatically trigger validation.

$('input:radio[name="Color"][value="Red"]')
    .prop('checked', true)
    .trigger('change')
    .valid();  // trigger validation on this element

Your CodePen updated: codepen.io/anon/pen/RQOKZZ

Sparky
  • 98,165
  • 25
  • 199
  • 285