Reputation: 93
<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
I'm trying to add a class in a div only if the input field has value. I mean if we put text in input field the div automatically should add a class it's self. Bu the only problem is we can't give any class name or Id to input.
Using this script about we can add class when we click on input. But we need to do more.
Can we do that?
Upvotes: 0
Views: 914
Reputation: 2498
Here input
event fires on Keyboard input, Mouse Drag, Autofill, and Copy-Paste.
You can try below code -
function toggleParentClass(elem) {
console.log(elem.val());
if (elem.val().length)
elem.closest('.parent').addClass('focused');
else
elem.closest('.parent').removeClass('focused');
}
$('.parent').on('input', function() {
toggleParentClass($(this).find('input'));
});
.focused {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="text" />
</div>
Upvotes: 0
Reputation: 68933
You can use input
instead of focus
. You also have to check the value to add/remove the class. Try the following way:
$(document).ready(function(){
$('.parent > *').focus();
$('.parent > *')
.on('input', function() {
if($(this).val().trim() != '')
$(this).parent().addClass('focused');
else
$(this).parent().removeClass('focused');
});
});
.focused{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">Test <input type="text" /> </div>
Upvotes: 1
Reputation: 2086
How about putting a event-listener on the input field.
If the input box goes empty, remove the class. Otherwise, add the required class.
Closest helps you find the closest member with the given selection criteria.
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$('input').change(function(){
if( $(this).val().trim() === '' ){//Empty input box
$(this).closest('.parent').removeClass('focused');
}
else{
$(this).closest('.parent').addClass('focused');
}
}
);
Upvotes: 0
Reputation: 34107
With the html you provided, this should work
$('.parent > *')
.focus(function() {
if( $(this).val().length) $(this).parent().addClass('focused');
})
.blur(function() {
if( $(this).val().length) $(this).parent().removeClass('focused');
});
Update after OP comment
<div class="some-div">Hello</div>
<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$(".some-div").addClass('focused');
})
.blur(function() {
$('.some-div').removeClass('focused');
});
Upvotes: 0
Reputation: 44087
Sure, just use .parent > input
:
$('.parent > input')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
Upvotes: 0