只有在填充了所有输入字段后才启用元素.可重复使用的功能



我正在尝试编写一个可重复使用的函数,该函数在所有输入字段中循环,如果任何字段为空,我希望另一个元素(a href或按钮(切换类名(禁用(。

目前,它对第一个输入有效,但对第二个输入无效,我认为这与jquery选择器有关。

JS:

const toggleElem = () => {
const parent = $('.fileUploader--videos');
const $input = parent.find('[type="text"]'); // I think this is the issue
const $wrapper = parent.find('.fileUploader-wrapper');
const visibleClass = 'visible';
$input.on('change input', () => {
toggleElemValidInput($input, $wrapper, visibleClass);
});
};
toggleElem();
const toggleElemValidInput = (input, elem, className) => {
input.each(function() {
if ($(this).val() !== '') {
// also would prefer if ($(this).val().length !== 0)
elem.addClass(className);
} else {
elem.removeClass(className);
}
});
};

HTML:

<div class="fileUploader col fileUploader--videos hasAdvancedUpload" data-action="/api/v1/ProductMediaVideoUploadApi" data-method="post">
<label for="videoTitle" class="mb-3">
<input type="text" name="videoTitle" value="" class="form-control" placeholder="Add video title" autocomplete="off">
</label>
<label for="videoUrl" class="mb-3">
<input type="text" name="videoUrl" value="" class="form-control" placeholder="Add video url" autocomplete="off">
</label>
<i class="fileUploader__icon fa fa-film"></i>
<div class="fileUploader__input">
<input class="fileUploader__file" type="file" name="file-videos" id="file-videos" accept="image/x-png,image/gif,image/jpeg">
<label for="file-videos">Click to add a video thumbnail</label>
<p class="fileUploader__dragndrop"> or drag it here</p>
<ul class="small">
<li>File formats: </li>
<li>File size: <span class="file-size-max"></span></li>
</ul>
</div>
<div class="fileUploader__uploading">Uploading...</div>
<div class="fileUploader__success">Complete</div>
<div class="fileUploader__error">Error. <span></span></div>
<a href="#" class="fileUploader__restart fa fa-redo-alt"></a>
<div class="fileUploader-wrapper mt-3 text-right">
<a href="#" class="btn btn-primary btn-submit">Submit</a>
</div>
</div>

我在这里做了一把小提琴:https://jsfiddle.net/lharby/zygw72pr/

我有点理解创建这个函数并且只针对一个选择器,但我的目标是使它可重用,无论是1个输入还是100个输入都不重要。

TIA-

过滤所有文本框。如果没有空类,请将该类设置为可见。

var query = "input[type="text"]";
$(query).on("input change", () =>
{
if($(query).filter((a, b) => $(b).val().length == 0).length == 0)
$(".fileUploader-wrapper").addClass("visible");
else
$(".fileUploader-wrapper").removeClass("visible");
});

问题是类的切换只取决于集合中的最后一个输入,就像你在循环中写的那样。

您可以使用filter()来获取空的集合(如果有的话(,并使用该集合长度来确定类的切换。

toggleClass()与它的布尔第二个参数一起使用也比在条件中同时写入addClass()removeClass()更简单

类似于:

const toggleElemValidInput = (input, elem, className) => {
const hasEmpty = !!input.filter((i,el) => !el.value.trim()).length;
elem.toggleClass(className, hasEmpty);
};

最新更新