Michael Michael - 1 month ago 11
jQuery Question

Trying to apply a class to a parent

I'm trying to add a class to a parent of an element on focus on an input field. There is a focus on the input field, but as there is a field add on I want the focus to be round the whole thing hence using the .parent(). I've tried the below and a few other things but can't get it to work.

Here is the HTML:

<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control mort-calc-field comma" id="pp">
</div>


Here is the jQuery:

$(document).ready(function(){
$('.mort-calc-field').onfocus(function(){
$(this).parent().addClass('calc-box-shadow');
});
$('.mort-calc-field').focusout(function(){
$(this).parent().removeClass('calc-box-shadow');
});
});

Answer Source

Try this:

   $(document).ready(function(){
     $('.mort-calc-field').focus(function(){
     $(this).parent().addClass('calc-box-shadow');
     });
     $('.mort-calc-field').blur(function(){
     $(this).parent().removeClass('calc-box-shadow');
     });
   });