JSamarjiev JSamarjiev - 5 months ago 12
Javascript Question

Validating Bootstrap form with jQuery

I have a Bootstrap form and I am basically trying to loop through all input fields, check if they have a

required
class and their value is
null
, if so add some CSS as an error indicator. For some reason the
if
statement is not working.

My code is:

$("#orderForm").on("submit", function(e) {
var formInputFields = $(".form-control")
formInputFields.each(function(i) {
if (formInputFields[i].hasClass("required") && formInputFields[i].val() === "null") {
e.preventDefault();
formInputFields.css("border", "2px solid #741e4f");
}
});


});

HTML is along these lines, but longer, same structure though, the
form-group
div is repeated:

<form class="form-horizontal" id="orderForm">
<div class="form-group">
<label for="" class="col-sm-4 control-label">Lorem</label>
<div class="col-sm-6">
<select name="" id="" class="form-control required">
<option value=""></option>
<option value="lorem">lorem</option>
<option value="ipsun">ipsun</option>
</select>
</div>
</div>



Answer

Your code threw error when you say formInputFields[i].hasClass because formInputFields was a jquery object but not formInputFields[i]. Since you were using $.each, the 2nd parameter would have given you current element and instead of formInputFields[i], you could just use that 2nd parameter. Also, when you say cur.val()==="null" it will be strong comparison between left and right i.e. both should match by value and type which always failed here. So just check the length of val and if it is 0 that will be invalid element. Below are the changes I've made. Check and it and let me know if you face any issues.

$("#orderForm").on("submit", function(e) {
  var formInputFields = $(".form-control")
  formInputFields.each(function(i, v) {
    var cur = $(v);
    if (cur.hasClass("required") && !(cur.val().length)) {
      e.preventDefault();
      cur.css("border", "2px solid #741e4f");
    }
    else
      cur.css("border", "");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<form class="form-horizontal" id="orderForm">
  <div class="form-group">
    <label for="" class="col-sm-4 control-label">Lorem</label>
    <div class="col-sm-6">
      <select name="" id="" class="form-control required">
        <option value=""></option>
        <option value="lorem">lorem</option>
        <option value="ipsun">ipsun</option>
      </select>
    </div>
  </div>
  <input class="btn btn-info" type="submit" value="Submit" />
</form>