下面是我的HTML CSS代码的一部分。我希望在按下“注册”按钮时填写所有输入。如果我没有地址,则会在输入字段上弹出一个弹出警告。我希望下拉菜单也一样。我知道由于JavaScript代码,当按下“注册”按钮时,该代码会向您发出警告。但是我想知道:是否可以将警告的位置从“注册”按钮更改为下拉菜单?
感谢您的所有帮助。
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" method="post" action=".">
<div class="form-group">
<label for="adress" class="form-text">Adress</label>
<input type="text" class="form-control" id="adress" placeholder="Rainbow 3" name="adress" required>
</div>
<div class="form-row">
<div class="form-group col-md-8" style="height:70px">
<label for="inputState" class="form-text">State</label>
<select id="inputState" class="form-control" name="state" required>
<option selected disabled value="0"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<button href="/oglasi/" type="submit" class="btn btn-outline-secondary" role="button" aria-pressed="true" onclick="check(this)">Register</button>
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (document.getElementById('inputState').value == "0") {
input.setCustomValidity('Choose state.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
<br>
</form>
</div>
</body>
</html>
答案 0 :(得分:0)
您需要setCustomValidity
才能选择元素
function check(input) {
const inputStateElm = document.getElementById('inputState');
if (inputStateElm.value == "0") {
inputStateElm.setCustomValidity('Choose state.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
-
完整代码
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" method="post" action=".">
<div class="form-group">
<label for="adress" class="form-text">Adress</label>
<input type="text" class="form-control" id="adress" placeholder="Rainbow 3" name="adress" required>
</div>
<div class="form-row">
<div class="form-group col-md-8" style="height:70px">
<label for="inputState" class="form-text">State</label>
<select id="inputState" class="form-control" name="state" required>
<option selected disabled value="0"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<button href="/oglasi/" type="submit" class="btn btn-outline-secondary" role="button" aria-pressed="true" onclick="check(this)">Register</button>
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
const inputStateElm = document.getElementById('inputState');
if (inputStateElm.value == "0") {
debugger;
inputStateElm.setCustomValidity('Choose state.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
<br>
</form>
</div>
</body>
</html>