0

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/

6
  • What is the expected behavior? Commented Jan 27, 2015 at 20:04
  • @Ionica it is to apply the bootstrap has warning class which gives the input a red boarder Commented Jan 27, 2015 at 20:05
  • You can provide the HTML too? Maybe a JSFiddle? Commented Jan 27, 2015 at 20:07
  • 1
    Is that code waiting the DOM to be ready? Commented Jan 27, 2015 at 20:13
  • Possible duplicate of Check if inputs are empty using jQuery Commented Feb 5, 2016 at 15:41

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to submit. If i click into a text field, and then if you click out it will validate if it is blank or not
@CamSonaris See the edit. Note you have to make sure that the elements exist on the page when you add the even listener.
0
$('#registration-form input').blur(function() {

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

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

    }

});

4 Comments

This doesn't make sense since !"" is true.
What doesn't make sense about it? If the value of the active input is empty then it will apply the class.
this doesnt work either. in the debugger it seems that it never hits the if statement
Post the relevant HTML and make sure jQuery is included, cause that should have worked if the selector was correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.