【发布时间】:2019-09-08 19:39:28
【问题描述】:
我创建了一个函数,它应该检查我的输入字段,类型复选框是否已被选中...但是每当我检查我的输入字段时,我希望设置为必需的输入字段没有获得所需的属性。
我基本上尝试了这个主题的所有内容:jQuery add required to input fields
并阅读此主题以希望找到一些东西:.prop() vs .attr()
但不幸的是,没有一个主题对我有太大帮助。因此,要么我在代码中的某个地方出错,要么所需的属性有点错误。
我通过我的输入字段(onclick 事件)调用该函数。 我已经检查了选择器是否正确,它们是正确的。
这就是我的 HTML 的样子:
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" onclick="is_required()" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
这就是我调用函数的方式:
<input class="custom-control-input" onclick="is_required()" type="checkbox" value="vegan" name="vegetarisch[]">
function is_required() {
//check whether the checkbox has been checked or not
//if yes, make the other input fields inside the row required
// variable odin = the row wrapped around the cols
$('input[name="vegetarisch[]"]').each(function(index, thisElement) {
if($(thisElement).is(':checked')) {
let odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}
所以我希望实现的目标是:选中复选框后,我希望在该行内有另外 2 个输入字段以获得“必需”属性。
【问题讨论】:
-
请添加 all 相关代码(其他 HTML 字段和任何 CSS),以便我们可以复制您的问题。
-
您的代码似乎工作正常:jsfiddle.net/o7ye5rhx,但这是基于您使用的 JS 方法对 HTML 的假设。请将 HTML 添加到问题中,并检查控制台中是否有任何错误。另请注意,您应该使用不显眼的事件处理程序而不是 HTML 中的
on*属性 -
变量
odin应该在.each()回调外部if中声明。现在,有 两个odin变量:一个在if块中,一个是全局变量。 -
因为我已经输入了它,这是我的小提琴,有两行和优化的代码:jsfiddle.net/khrismuc/y62btawu
标签: javascript jquery