javascript - JS - 当输入有值时向表单添加类
问题描述
我有一个表单,其中包含一个用于电子邮件地址的输入字段。现在我想<form>
在输入有值时添加一个类,但我不知道该怎么做。
当输入具有值时,我正在使用此代码向标签添加一个类,但我不能使其也适用于:
function checkForInputFooter(element) {
const $label = $(element).siblings('.raven-field-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.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
解决方案
您可以监听输入元素的“输入”事件并用于.closest(<selector>)
添加或删除类
$('input').on('input', function () {
if (!this.value) {
$(this).closest('form').removeClass('has-value');
} else {
$(this).closest('form').addClass('has-value');
}
})
推荐阅读
- android - 如何在不使用操作栏且没有任何物理按钮的情况下退出应用程序?
- oracle - 在 oracle 中使用 REGEXPR_SUBSTR 的模式匹配条件
- c - printf() 中的 %qu 格式代表什么
- javascript - JS 专注于超链接
- java - Spring boot 2 启用非安全 /health 端点
- sql-server - 查询统计满足特定条件的数据
- postgresql - 为什么索引会增加 postgres 中的执行时间?
- magento - 如何在magento 2后端保存盘点之前进行验证
- python-3.x - 获取python窗口中的空闲CPU计数
- c# - 以 xamarin 形式连接 3 个表