[英]Disable/Enable "save-button" using JavaScript
我已經將“禁用”屬性設置為我的保存按鈕,我的目標是在用戶填寫表單中的所有輸入字段時啟用它。
現在它有效,因為我在最后一個輸入字段中設置了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');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.