[英]Html “required” attribute doesn't work when i submit a form via a Bootstrap model
[英]HTML Bootstrap Form - "required" label doesn't work with JS script
各位晚上好,
我正在編碼的網站有問題。 我在 index.html 中實現了一個引導程序表單,並且編寫了一個 Javascript 腳本,它鏈接到 HTML。
這是 HTML:
<div class="container">
<div style="text-align:center">
<br>
<h5><span class="badge bg-primary shadow rounded">Enregistrer un résultat</span></h5>
<br>
</div>
<div class="container">
<div class="row">
<div class="col align-items-stretch" id="patient_form">
<div class="card shadow mb-5 bg-body rounded text-center" style='height: 430px;'>
<div class="card-header"><strong>Remplissez les informations du patient</strong></div>
<div class="card-body">
<p class="card-text">
<form class="form-inline" role="form">
<div class="form-floating mb-2">
<input class="form-control" id="patient_prenom" autocomplete="off" required/>
<label for="patient_prenom">Prénom</label>
</div>
<div class="form-floating mb-2">
<input class="form-control" id="patient_nom" autocomplete="off" required/>
<label for="patient_nom">Nom</label>
</div>
<div class="form-floating mb-2">
<input class="form-control" id="patient_date_naissance" type="date" required>
<label for="patient_date_naissance">Date de naissance</label>
</div>
<br>
<div class="text-center">
<button onclick="searchPatient()" type="submit" class="btn btn-primary btn-sm">Rechercher le patient</button>
</div>
</form>
</p>
</div>
</div>
</div>
這是 Javascript 腳本:
function searchPatient() {
prenom = document.getElementById('patient_prenom').value;
nom = document.getElementById('patient_nom').value;
date_naissance = document.getElementById('patient_date_naissance').value;
document.getElementById("patient_form").style.display = "none";
document.getElementById("intervention_form").style.display = "block";
document.getElementById("patient_recap").style.display = "block";
document.getElementById('patient_recap_text').innerHTML += '<h5>' + prenom + ' ' + nom + '<h5>' + '<h6>' + date_naissance + ' ' + '<h6>';
}
使用此配置,我的第一個表單中的“必需”label 不起作用。 但是,只要我刪除將 Javascript 鏈接到 HTML 的行,它就會起作用。
你能幫我解決這個問題嗎?
非常感謝你!!
看起來將onclick="searchPatient"
添加到提交按鈕意味着它將立即運行 function 並跳過表單驗證。 根據這個答案,如果您通過 JS 提交表單,則必須自己進行驗證。 這是我能夠做到的:
首先,您需要要檢查驗證的表單的句柄。 最簡單的方法是在表單元素上使用id="form"
。
然后,您只需調用formElement.checkValidity()
,如果它返回 false,則不會調用您的提交邏輯。 例如:
function searchPatient() {
const form = document.getElementById('form');
if (!form.checkValidity()) {
return;
}
// ... rest of function like normal
}
現在,當我單擊該按鈕時,會出現“此字段為必填”彈出窗口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.