I have a div with a form field and a button that I would like to have parsley validate all the form fields in that div that have the proper data-validate
attribute. I need it to work no matter how many form fields are in the div. So it needs to work on inputs, textareas, and select fields.
HTML:
<div id="parsley-div">
<div class="form-group">
<label for="city">City</label>
<input id="city-test" type="text" class="form-control" data-parsley-required data-parsley-required-message="Please enter a city name.">
</div>
<button class="btn btn-primary">Save Changes</button>
</div>
JS:
$('#parsley-div').find('button').click(function(){
$('#parsley-div').parsley().validate();
});
Unfortunately, this isn't working. I noticed it works if there is a form tag around the form fields, but I need it to be a div. I have created a JSFiddle that shows both cases: https://jsfiddle.net/8rkxzjx1/2/
How can I have parsley validate all form fields with data-parsley
attributes within a specified div? If possible, please edit the JSFiddle to show the correct implementation. Thank you.
Edit:
I figured out this works, but it doesn't feel very efficient:
$('#parsley-div').find( "input, textarea, select" ).each(function (index, value) {
$(this).parsley().validate();
});
You could use
$('#parsley-div :input:not(:button)').parsley().validate();
See fiddle.
Edit
Looks like the above code won't work. The following can be used as the OP suggested.
$('#parsley-div :input:not(:button)').each(function (index, value) {
$(this).parsley().validate();
});
Here is the new fiddle.
Or the content can be wrapped in a form element and then be validated as follows:
$("#parsley-div").wrap("<form id='parsley-form'></form>");
$('#parsley-div').find('button').click(function() {
$('#parsley-form').parsley().validate();
});
Or since the OP does not want to have a form element in Dom, content can be wrapped in a form element and then the form can be removed after validation.
$('#parsley-div').find('button').click(function() {
$("#parsley-div").wrap("<form id='parsley-form'></form>");
$('#parsley-form').parsley().validate();
$("#parsley-div").unwrap();
});
Links to fiddle-wrap and fiddle-wrap-unwrap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With