Issue
If an input is in focus or has a value, I want to add a class to all inputs parent .field div. For example on the product page review form or on the checkout page shipping form. If the input is in focus I would add an "active" class and if the input has a value I would add the class "hasavalue."
When I try to use jquery, nothing happens on the product page review form inputs or on the checkout page inputs.
Here's the jquery I am using:
requirejs(['jquery'],function($){
$(document).ready(function(){
$('.field input').focus(function () {
$(this).parent().parent().addClass('active');
}).blur(function () {
$(this).parent().parent().removeClass('active');
});
$('.field input').blur(function(){
if ( $(this).val() ) {
$(this).parent().parent().addClass('hasavalue');
} else{
$(this).parent().parent().removeClass('hasavalue');
}
});
});
});
Do I need to use knockout? If so, how can I translate this simple jquery to work with all inputs in Magento?
Solution
If the fields are not loaded yet, you need to delegate the event handlers. However, 'focus' and 'blur' do not bubble, so you need to use jQuery's .on('focusin')
and .on('focusout')
https://stackoverflow.com/a/14496244/6127393
$(document).ready(function() {
$('body').on('focusin', '.field input', function() {
$(this).closest('.field').addClass('active');
}).on('focusout', '.field input', function() {
let fieldDiv = $(this).closest('.field');
fieldDiv.removeClass('active');
// toggleClass eliminates need for if else, just put the test as second parameter, true adds class while false removes it
fieldDiv.toggleClass('hasavalue', ($(this).val() !== ''));
})
// adding a field afterwards just for demonstration to show it still works
$('<div class="field"><label>loaded after document ready</label><br><input></div>').appendTo('body')
});
/* just example for visual verification */
.field {
padding: 1em;
border: 1px solid white;
background: orange;
}
.field.active {
border: 1px solid black;
}
.field.hasavalue {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- structure does not matter as long as there is an input inside .field -->
<div class="field">
<input>
</div>
<div class="field">
<div>
<input>
</div>
</div>
<div class="field">
<div>
<div>
<div>
<input>
</div>
</div>
</div>
</div>
Answered By - Arleigh Hix Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.