我有一些單選按鈕和一些用于驗證單選按鈕的 JavaScript。
HTML:
<html>
<head>
</head>
<body>
<input type="radio" name="radios" id="first-radio" value="option1" required>
<label for="first-radio">
Radio 1
</label>
<input type="radio" name="radios" id="second-radio" value="option2">
<label for="second-radio">
Radio 2
</label>
<input id="txt-box" type="text" required />
<button id="btn-next">
Btn Next
</button>
<script src="radios.js"></script>
</body>
</html>
JavaScript:
(function () {
function validateTextbox() {
document.getElementById('txt-box').reportValidity();
}
function validateRadios() {
document.getElementById('first-radio').reportValidity();
}
// document.getElementById('btn-next').addEventListener('click', validateTextbox);
document.getElementById('btn-next').addEventListener('click', validateRadios);
})();
我已將name單選按鈕設定為將它們分組并添加required到其中之一。
我為按鈕添加了一個事件偵聽器,當我單擊按鈕時,我檢查是否使用reportValidity.
該代碼似乎有效,除了當我單擊按鈕時,Chrome 中的“請選擇這些選項之一”驗證警告訊息不會顯示,除非我將游標從按鈕上移開。
任何線索為什么會這樣以及我需要做什么?
如果我對文本框進行同樣的嘗試,文本框會在我單擊按鈕后立即顯示驗證警告訊息“請填寫此欄位”。
Edit: I tried the same in Firefox and Edge and both the 'Please select one of these options' and 'Please fill out this field' show up immediately after I click the button.
Is this a Chrome bug?
uj5u.com熱心網友回復:
這是我的解決方案:
document.getElementById('btn-next').addEventListener('click', validateRadios);
function validateRadios() {
console.log(document.getElementById('ok').reportValidity());
}
<form id="ok">
<input type="radio" name="radios" id="first-radio" value="option1" required>
<label for="first-radio">
Radio 1
</label>
<input type="radio" name="radios" id="second-radio" value="option2">
<label for="second-radio">
Radio 2
</label>
<input id="txt-box" type="text" required />
<button id="btn-next">
Btn Next
</button>
</form>
uj5u.com熱心網友回復:
您的目的是檢查單選按鈕是否被選中。方法應該是您在默認情況下保持選中其中一個選項。
<input type="radio" name="radios" id="first-radio" value="option1" checked>
所以,而不是必需的,把檢查的屬性。
uj5u.com熱心網友回復:
// On clicking submit do following
$("#btn-next").click(function() {
var atLeastOneChecked = false;
$("input[type=radio]").each(function() {
// If radio button not checked
// display alert message
if ($(this).attr("checked") != "checked") {
// Alert message by displaying
// error message
$("#msg").html(
"<span class='alert alert-danger' id='error'>"
"Please Choose atleast one</span>");
}
});
});
您必須遍歷每個單選按鈕并檢查是否選中了其中的任何一個。以下是我根據您的需要從中提取和修改的網址。
如何顯示無線電驗證
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345564.html
標籤:javascript html google-chrome
上一篇:曾經可以作業的SeleniumPython代碼現在打開瀏覽器,然后卡在“data:,”中。說“chrome無法訪問”
