【问题标题】:JS - Add class to form when input has valueJS - 当输入有值时向表单添加类
【发布时间】:2020-08-05 08:07:07
【问题描述】:

我有一个表单,其中包含一个用于电子邮件地址的输入字段。现在我想在输入有值时向<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

【问题讨论】:

  • 您能为此创建一个codepen吗?
  • @TechnoTech Pen 已添加到问题中。
  • 您的代码在标签上运行良好,您的意思是要向表单添加相同的类吗?
  • @HamzaDahmoun 是的,这就是我需要的,将类也添加到
    元素中。

标签: javascript css forms class


【解决方案1】:

这是使用 jQuery 的解决方案:

function checkForInputFooter(element) {
    // element is passed to the function ^
        
    const $label = $(element).siblings('.raven-field-label');      
    var $element = $(element);
    if ($element.val().length > 0) {
        $label.addClass('input-has-value');
        $element.closest('form').addClass('input-has-value');
    } else {
        $label.removeClass('input-has-value');
        $element.closest('form').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);  
});

我已经更新了你的笔here

【讨论】:

  • 太棒了!谢谢!
【解决方案2】:

在这里,使用 javascript vanilla。我选择了标签标签广告表单标签并根据元素值添加/删除了类,但首先您应该将 id="myForm" 添加到您的表单 html 标记中。祝你好运。

function checkForInputFooter(element) {
    // element is passed to the function ^
    let label = element.parentNode.querySelector('.raven-field-label');
    let myForm = document.getElementById("myform");
    let inputValue = element.value;
    if(inputValue != "" && inputValue != null){          
      label.classList.add('input-has-value');
      myForm.classList.add('input-has-value');
    }
    else{
      label.classList.remove('input-has-value');
      myForm.classList.remove('input-has-value');
    }
    }

【讨论】:

    【解决方案3】:

    可以监听输入元素的'input'事件并使用.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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 2016-01-30
      • 1970-01-01
      • 2023-03-13
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多