使用 JavaScript 禁用/启用"save-button"



我已经为我的保存按钮设置了属性"disable",我的目标是在用户填写表单中的所有输入字段时启用它。

目前它是有效的,因为我在最后一个输入字段中设置了onkeyup="checkForm(this)",但这不是解决问题的明智方法。

这是我表单中的html代码:

div class="page" id="create__book__formular">
<div class="page__formular">
<h3 id="formualer__name">Formular</h3>
<label>Name:
<input type="text" placeholder="Name" id="title" >
</label>
<label>Autor:
<input type="text" placeholder="Autor" id="autor">
</label>
<label>ISBN:
<input type="text" placeholder="ISBN" id="isbn">
</label>
<label>Anazhl:
<input type="text" placeholder="Anazhl" id="number">
</label>
<label>Verlag:
<input type="text" onkeyup="checkForm(this)" placeholder="Verlag" id="publishing">
</label>
<button type="button" class="btn btn-success create__book__formular" id="save--button" disabled="disabled">
save
</button>
<button type=" button " class="btn btn-light create__book__formular" id="back--button">
back
</button>
</div>
</div>

这是我的JavaScript代码:

function checkForm(create__book__formular) {
var bt = document.getElementById('save--button');
if (create__book__formular.value != '') {
bt.disabled = false;
} else {
bt.disabled = true;
}

}

谢谢你的帮助!

我发现下面的帖子提出了类似的问题。

它们提供以下代码:

(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()

如果至少有1个字段为空,则此代码应禁用提交按钮。

谢谢!我在没有jQuery的情况下找到了它,这是我的解决方案。

//9 Disable button in the form
const inputName = document.getElementById('title');
const inputAutor = document.getElementById('autor');
const inputIsbn = document.getElementById('isbn');
const inputNumber = document.getElementById('number');
const inputPublishing = document.getElementById('publishing');
const saveBtn = document.getElementById('save--button');
const form = document.getElementById('form');

form.addEventListener('input', showButton);
function showButton() {
if (inputName.value.length > 0 && inputAutor.value.length > 0 &&
inputIsbn.value.length > 0 && inputNumber.value.length > 0 &&
inputPublishing.value.length > 0) {
saveBtn.removeAttribute('disabled');
} else {
saveBtn.setAttribute('disabled', 'disabled');
}
}

最新更新