-1

I am working on jquery form validation, using the jQuery .validate plugin. There is a text field (name: "yo_text") that is required only when a radio button (in this case, "Hey Yo") is checked.

Now jQuery can tell yo_text depends on "Hey Yo" being selected, but an error crops up every time when yo_text blurs and is not empty. The error message at the text field does not go away too, if previous check said it was invalid (that is, yo_text being empty)

The error:

Uncaught TypeError: Cannot read property 'call' of undefined. Exception occurred when checking element , check the 'depends' method.

I had simply modified the code form .validate's example (see below), but now the mysterious error appears. I can't figure out where the problem comes from.

So the markup:

<form>
  <div class="radio">
    <label>
      <input type="radio" name="selection" value="yo"> Hey Yo
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" name="selection" value="ya"> Hey Ya
    </label>
  </div>
  <input class="form-control" type="text" name="yo_text" placeholder="Enter if yo">
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

And the script:

var form = $('form');

function isYo() {
  return form.find('input[type="radio"][name="selection"][value="yo"]')
}
form.validate({
  rules: {
    selection: 'required'
    , yo_text: {
      required: true,
      depends: isYo
    }
  }
});

And the example I modified from in .validate's documentation:

$("#myform").validate({
  rules: {
    contact: {
      required: true,
      email: {
        depends: function(element) {
          return $("#contactform_email").is(":checked");
        }
      }
    }
  }
});

And a JSFiddle for reference:

https://jsfiddle.net/vzj1ckbx/

Thanks for any help in advance!

Sparky
  • 98,165
  • 25
  • 199
  • 285
Chung Lun Yuen
  • 319
  • 4
  • 15

1 Answers1

1

There is an issue in your function isYo, I think it should return a Boolean value which was not. In your case it will return the element. Also some modifications in the validate also.

https://jsfiddle.net/vzj1ckbx/4/

var form = $('form');

function isYo() {
 return $('input[type="radio"][name="selection"][value="yo"]').is(':checked');

}
form.validate({
    rules: {
        "yo_text": {            
            required: {
                param:true,
                depends: isYo
            }
        }
    },
    submitHandler: function () {
            alert('Ho hey')
        event.preventDefault();
        return false;
    }
});
Vineesh
  • 3,762
  • 20
  • 37
  • Thanks! This works! Also found the latter part of the solution [here](https://stackoverflow.com/questions/9026740/jquery-validator-depends-method-undefined). – Chung Lun Yuen Jul 27 '17 at 04:16