Alex N
Alex N

Reputation: 1121

How get parent div

Good day.

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess">
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
</div>

I would like that when input lose focus (focusout) in class element div with class form-group add class add, but only one.

For ex. if input with id=inputError loses focus in class element <div class="form-group has-error"> add class add: <div class="form-group has-error add">

And I would like that only in one element with class form-group add class "add".

I use code:

$(".form-control").focusout(function(){

})

but I don't know how get parent div with class form-group...

How make this?

Upvotes: 2

Views: 1916

Answers (5)

Serjik
Serjik

Reputation: 10971

$(".form-control").focusout(function(){
    $(this).parent().addClass('add');
})

Upvotes: 1

The Alpha
The Alpha

Reputation: 146269

You may try this

$(".form-control").on('focusout', function(){
    $(this).closest('.form-group').addClass('add');
});

or this one

$(".form-control").on('focusout', function(){
    $(this).parent().addClass('add');
});

Upvotes: 1

Aldi Unanto
Aldi Unanto

Reputation: 3682

$(".form-control").focusout(function(){
   $(this).parent('.form-group').addClass('add');
});

Upvotes: 1

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

You can also use parent() method

$(".form-control").focusout(function(){
    $(this).parent().addClass('add');
})

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388436

You can use .closest() to find out the nearest ancestor element matching the given selector

$(".form-control").focusout(function(){
    var $div = $(this).closest('.form-group').addClass('add')
})

in you case if the form-group element is always the direct parent of form-control element then you can even use .parent()

$(".form-control").focusout(function(){
    var $div = $(this).parent().addClass('add')
})

Upvotes: 6

Related Questions