user1571609
user1571609

Reputation:

Check if inputs are empty using jQuery before submitting

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display the bootstrap has warning class.

Here is my code:

$('#registration-form input').blur(function()
{
    if( !$(this).val() ) {
        $(this).parents('li').addClass('has-warning');
    }
});

What am I doing wrong?

Here is jsfiddle http://jsfiddle.net/f7gsgy93/

Upvotes: 0

Views: 5452

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113365

You have to catch the submit event on the form. If the input is invalid, then prevent the default behavior.

$("form").on("submit", function () {
    var isInvalid = false;
    $("input", this).each(function () {
        if (!$(this).val()) {
            isInvalid = true;
        }
    });
    if (isInvalid) {
        return false;
    }
});

If you only need to catch the blur event then, just do it!

$(document).ready(function() {
  var $error = $(".alert-danger");
  $("form input").on("blur", function() {
    if (!$(this).val()) {
      $error.removeClass("hide").text("No value");
    } else {
      $error.addClass("hide");
    }
  });
});
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <form action="">
    <input type="text" class="form-control" placeholder="Text input">
    <div class="errors">
      <div class="alert alert-danger hide"></div>
    </div>
  </form>
</div>

Upvotes: 2

Waxi
Waxi

Reputation: 1651

$('#registration-form input').blur(function() {

    if ($(this).val() == '') {

        $(this).parents('li').addClass('has-warning');

    }

});

Upvotes: 0

Related Questions