我有3个输入框。当用户在其中输入任何值时,我想调用函数以突出显示框。通过使用 keyup 功能,我能够实现它,但它也会触发其下一个输入元素的 keyup 功能。下面是我的代码
工作演示 - https://www.w3schools.com/code/tryit.asp?filename=G38SF7O5Q7MQ
<div>
<input type="text" class="cDate" />
<input type="text" class="cMonth" />
<input type="text" class="cYear" />
</div>
<div class="error-msg"></div>
<script>
$(document).ready(function(){
$('.cDate').on('keyup blur change', function(){
$(this).next().trigger('focus');
highlightInputs(this)
});
$('.cMonth').on('keyup blur change', function(){
$(this).next().trigger('focus');
highlightInputs(this)
});
$('.cYear').on('keyup blur change', function(){
$(this).trigger('focusout');
highlightInputs(this)
});
});
function highlightInputs(_inputs) {
$(_inputs).each(function(){
if($(this).val() == ''){
$(this).addClass('error');
$('.error-msg').text('Please enter valid date');
$('.error-msg').show();
}
else{
$(this).removeClass('error');
$('.error-msg').text('Please enter valid date');
$('.error-msg').hide();
}
});
}
</script>