首页 > 解决方案 > 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);  
});

笔:https ://codepen.io/mdia/pen/gOrOWMN

标签: javascriptcssformsclass

解决方案


您可以监听输入元素的“输入”事件并用于.closest(<selector>)添加或删除类

$('input').on('input', function () {
  if (!this.value) {
    $(this).closest('form').removeClass('has-value');
  } else {
    $(this).closest('form').addClass('has-value');
  }
})

编辑:https ://codepen.io/KlumperN/pen/xxVxdzy


推荐阅读