Reputation: 25
I can't get this simple jQuery onblur
handler to add the appropriate class. No errors are returned to the console and nothing happens on the blur event. What am I doing wrong?
I've verified that jQuery has been correctly loaded and is working properly.
$(document).ready(function() {
$('#nameInput').on('blur', function() {
$('#nameInput').addClass('has-success');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<form class="form-horizontal" id="form" name="contactform.htm" method="post" action="send_form_email.php">
<div id="nameInput" class="form-group">
<label for="first_name" class="col-sm-2 control-label lead">Name</label>
<div class="col-sm-10">
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="John Doe">
<span id="glyph" class="form-control-feedback"></span>
</div>
</div>
</form>
</div>
</div>
Upvotes: 0
Views: 1627
Reputation: 95017
The blur event does not bubble, therefore it will never reach the div. If you instead used the focusout event, it would work.
$(document).ready(function() {
$('#nameInput').on('focusout', function() {
$('#nameInput').addClass('has-success');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<form class="form-horizontal" id="form" name="contactform.htm" method="post" action="send_form_email.php">
<div id="nameInput" class="form-group">
<label for="first_name" class="col-sm-2 control-label lead">Name</label>
<div class="col-sm-10">
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="John Doe">
<span id="glyph" class="form-control-feedback"></span>
</div>
</div>
</form>
</div>
</div>
Upvotes: 2
Reputation: 13381
You add handler to div instead of input, but div not raise blur event. So you need just add handler to your input, like
$('#nameInput input').on('blur', function() {
$('#nameInput').addClass('has-success');
});
another solutions:
Upvotes: 1
Reputation: 157
you may want to test this
$(document).ready( function(){
$(document).on('blur', '#nameInput', function() {
$(this).addClass('has-success');
});
});
Upvotes: -1