1

I have a hidden field that gets populated (via Jquery) when a user clicks on a thumbnail image (with a class of 'thumbnail') using

<input type="hidden" id="DocThumbnail" name="DocThumbnail" value=""/>

and

$(".Thumbnail").click(function() {
    var thumbnailFile = $(this).attr("src");
    $("#DocThumbnail").val(thumbnailFile);
});

I have set up my jquery validation as follows:

$("#AddDocumentForm").validate({
    ignore: [], 
    rules: {
        DocThumbnail : { required : true}
    },
    messages: {
        DocThumbnail: "Please choose a thumbnail"
    }
});

When I click the submit button on the AddDocumentForm the error appears as the value of the hidden field is empty, however when I click on a thumbnail (with a class of 'thumbnail') then hidden field is populated but the validation alert stays on so the form will not submit.

Does anybody know how I can validate a jquery populated hidden field as if I don't add the ignore:[]; line then the hidden field is ignored in the validation

David
  • 106
  • 1
  • 12
  • if you're using version 1.9 or higher of the plugin, have you seen this: http://stackoverflow.com/questions/8466643/jquery-validate-enable-validation-for-hidden-fields? – Fayyaz Naqvi Oct 28 '15 at 11:20
  • using version 14 and yes I have seen that post but even adding $.validator.setDefaults({ ignore: '' }); outside of document.ready did not get it working – David Oct 28 '15 at 11:32

1 Answers1

1

You need to call the Validator.element method after you change the value of DocThumbnail. That tells jQuery Validate to re-check DocThumbnail which will make the error message disappear.

Your updated code would look like this:

var validator = $("#AddDocumentForm").validate({
    ignore: [], 
    rules: {
        DocThumbnail : { required : true}
    },
    messages: {
        DocThumbnail: "Please choose a thumbnail"
    }
});

$(".Thumbnail").click(function() {
    var thumbnailFile = $(this).attr("src");
    $("#DocThumbnail").val(thumbnailFile);
    validator.element($('#DocThumbnail'));
});

You can see a working example here: http://jsfiddle.net/ryleyb/r0rkfykg/

Ryley
  • 21,046
  • 2
  • 67
  • 81
  • Thanks Ryley, I hacked it by using Jquery within the $(".Thumbnail").click(function() to remove the error label created by the validation (if one existed) but your method is cleaner – David Oct 29 '15 at 16:06