user2818541 user2818541 - 3 months ago 12
HTML Question

Show Jquery Form Validation message Next to bootsrap Textbox

I have a form implemented using Bootstrap and now validating form using jquery validate plugin. Validations are working fine but I want to show validation messages next to textbox field but currently it is showing below to my text box.

Here is my html code:

<div class="form-group">
<div class="col-md-2">
<label for="forTypeName" class="control-label">Trainer Name</label>
</div>
<div class="col-md-10">
<input type="text" class="form-control" id="txtname" name="txtname">
</div>
</div>


and my JS Code is

var validator = $("#sjform").validate({
rules: {
txtname: "required"

},
messages: {
txtname: "Required"
},
errorPlacement: function (error, element) {
// error.appendTo($(element).parent().next());
error.insertAfter(element);
},

//highlight: function (element) {
// $(element).closest('.form-group').addClass('has-error');
//},
//unhighlight: function (element) {
// $(element).closest('.form-group').removeClass('has-error');
//},
highlight: function (element) {
$(element).parent().removeClass('has-success').addClass('has-error');
},
unhighlight: function (element) {
$(element).parent().removeClass('has-error').addClass('has-success');
},
errorElement: 'span',
errorClass: 'help-block',
submitHandler: function (form) {
form.submit();
}
});


devs any help please..

Answer

I suggest you use nested columns bootstrap technique, wrapping the field and the corresponding error in containers floating along each other.

<div class="col-xs-10">
      <div class="row">
          <div class="col-xs-9 field-div">
              <input type="text" class="form-control" id="txtname" name="txtname" />
          </div>
          <div class="col-xs-3 error-div"></div>          
      </div>
  </div>

So, add extra "row" + two div wrappers and adjust their width to your needs. I changed col-md to col-xs just for example sake, to make sure they always float at every resolution.

working demo