当我选中 livelongwarranty 复选框时,我可以从输入字段 Warranty_duration 中删除所需的 attr
years warrenty<label id="warrantyDurationlabel"><input name="warranty_duration" type="number" placeholder="aantal jaren garantie" min="1" size="25" required /></label>
levenlang<label id="livelongwarranty"><input name="livelong_warranty" type="checkbox" onclick="js/warrantyrequired.js" /></label>
我有以下 jquery:
$('#livelong_warranty').change(function () {
if($(this).is(':checked') {
$('#warranty_duration').removeAttr('required');
} else {
$('#warranty_duration').attr('required');
}});
最佳答案
我必须向您的输入添加 id 属性,因为它们没有 ID(您可以搜索名称,但我认为这不是您想要的)。名称主要用于通过 HTML/PHP 表单发送/获取数据,而 id 用于引用、样式以及 JavaScript 元素。
$('#livelong_warranty').on('change', function () {
$('#warranty_duration').attr('required',$('#livelong_warranty').is(":checked"));
console.log($('#warranty_duration').attr('required'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
years warrenty<label id="warrantyDurationlabel"><input name="warranty_duration" id="warranty_duration" type="number" placeholder="aantal jaren garantie" min="1" size="25" required /></label>
levenlang<label id="livelongwarranty"><input name="livelong_warranty" id="livelong_warranty" type="checkbox" /></label>
关于javascript - 删除 jquery 所需的 attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42796336/