Gautam P Behera Gautam P Behera - 6 months ago 13
Javascript Question

jquery form validation checkbox error display

I am currently using jquery form validation
for validating a form. A part of the form require the user to select a check box as per below;

<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<label class="checkbox-inline">
<input type="checkbox" class="chkbox" name="seltype" value="">Price is Firm
</label>
<label class="checkbox-inline">
<input type="checkbox" class="chkbox" name="seltype" value="">Negotiable
</label>
<label class="checkbox-inline">
<input type="checkbox" class="chkbox" name="seltype" value="">Swap/Trade
</label>
</div>
</div>


My issue is when user submits the form without selecting the chekbox the error display after the first checkbox, i.e. Price is firm. How do I bring the error message to the bottom, i.e. after Swap/Trade option.

jquery

$( document ).ready( function () {
$( "#fileupload" ).validate( {

rules: {seltype:"required"},
messages: {seltype:"Please select appropriate box"},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );

if ( element.prop( "type" ) === "checkbox" ) {
error.insertAfter( element.parent( "label" ) );
} else {
error.insertAfter( element );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-xs-5" ).addClass( "has-error" ).removeClass( "has-success" );
},
unhighlight: function (element, errorClass, validClass) {
$( element ).parents( ".col-xs-5" ).addClass( "has-success" ).removeClass( "has-error" );
}
} );

} );

Answer

In your current code you specify to insert it after the label:

error.insertAfter( element.parent( "label" ) );

So just change that to insert it after the label's parent div:

error.insertAfter( element.parent( "label" ).parent() );

Or after the last label:

error.insertAfter( element.parent( "label" ).siblings(':last') );