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


HUH函数
浏览 92回答 3
3回答

慕仙森

这是使用 jQuery 的解决方案:function checkForInputFooter(element) {&nbsp; &nbsp; // element is passed to the function ^&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const $label = $(element).siblings('.raven-field-label');&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; var $element = $(element);&nbsp; &nbsp; if ($element.val().length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; $label.addClass('input-has-value');&nbsp; &nbsp; &nbsp; &nbsp; $element.closest('form').addClass('input-has-value');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $label.removeClass('input-has-value');&nbsp; &nbsp; &nbsp; &nbsp; $element.closest('form').removeClass('input-has-value');&nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp;&nbsp;// The lines below are executed on page load$('input.raven-field').each(function() {&nbsp; &nbsp; checkForInputFooter(this);});&nbsp; &nbsp;&nbsp;// The lines below (inside) are executed on change & keyup$('input.raven-field').on('change keyup', function() {&nbsp; &nbsp; checkForInputFooter(this);&nbsp;&nbsp;});我在这里更新了你的笔。

萧十郎

您可以收听输入元素的“输入”事件并用于.closest(<selector>)添加或删除类$('input').on('input', function () {&nbsp; if (!this.value) {&nbsp; &nbsp; $(this).closest('form').removeClass('has-value');&nbsp; } else {&nbsp; &nbsp; $(this).closest('form').addClass('has-value');&nbsp; }})编辑:https ://codepen.io/KlumperN/pen/xxVxdzy

三国纷争

在这里,使用 javascript vanilla。我选择了标签标签和表单标签,并根据元素值添加/删除了类,但首先您应该将 id="myForm" 添加到您的表单 html 标签中。祝你好运。function checkForInputFooter(element) {&nbsp; &nbsp; // element is passed to the function ^&nbsp; &nbsp; let label = element.parentNode.querySelector('.raven-field-label');&nbsp; &nbsp; let myForm = document.getElementById("myform");&nbsp; &nbsp; let inputValue = element.value;&nbsp; &nbsp; if(inputValue != "" && inputValue != null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; label.classList.add('input-has-value');&nbsp; &nbsp; &nbsp; myForm.classList.add('input-has-value');&nbsp; &nbsp; }&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; label.classList.remove('input-has-value');&nbsp; &nbsp; &nbsp; myForm.classList.remove('input-has-value');&nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript