I'm sure there are many similar questions here but still i can't find an answer to this. What i want is to add a class to the label on document ready if the input[type="text"] has a value and remove that class if the user will delete that input value ( better said, remove the label class if the input has no value on blur ).
Code so far:
<div class="input-wrap">
<input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" />
<label class="demo-label" for="textdemo">{L_USERNAME}</label>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
$('.input-wrap .textdemo').val() ) {
$('label.demo-label').addClass('input-has-value');
}
});
</script>
This should do the trick:
function checkForInput(element) {
// element is passed to the function ^
const $label = $(element).siblings('label');
if ($(element).val().length > 0) {
$label.addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.textdemo').each(function() {
checkForInput(this);
});
// The lines below (inside) are executed on change & keyup
$('input.textdemo').on('change keyup', function() {
checkForInput(this);
});
label.input-has-value {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-wrap">
<input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" />
<label class="demo-label" for="textdemo">{L_USERNAME}</label>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With