gpt4 book ai didi

javascript - 如何使用 JavaScript 验证 HTML 中的 "Select"标签

转载 作者:可可西里 更新时间:2023-11-01 13:05:40 24 4
gpt4 key购买 nike

<form action="#" class="group" method="post" onsubmit="return checkforblank()">
<legend><span class="number">1</span>Departing & Arriving</legend>
<fielset class="col-sm-6">
<label for="FDestination">From</label>
<select name="Location" id="Location">
<option value="Please Select">Please Select</option>
<option value="Newport">Newport</option>
<option value="Mahdi">Mahdi</option>
<option value="Cardiff">Cardiff</option>
<option value="Cilo">Cilo is</option>
</select>
</fieldset>
</form>

<script>
function checkforblank(){
if (document.getElementsByID('Location').value== "Please Select") {
alert('Please enter first name');
document.getElementById('Location').style.borderColor = "red";
return false;
}
}
</script>

当用户从字段集中选择“请选择”选项时,如何显示错误?

最佳答案

How can I display error when user chooses "Please Select" option from fieldset?

您已经在验证表单提交,现在您只需要为 select onchange 添加相同的验证函数:

function checkforblank() {

var location = document.getElementById('Location');
var invalid = location.value == "Please Select";

if (invalid) {
alert('Please enter first name');
location.className = 'error';
}
else {
location.className = '';
}

return !invalid;
}
.error {border: 1px red solid;}
<form action="#" class="group" method="post" onsubmit="return checkforblank()">
<legend><span class="number">1</span>Departing & Arriving</legend>
<fielset class="col-sm-6">
<label for="FDestination">From</label>
<select name="Location" id="Location" onchange="checkforblank()">
<option value="Please Select">Please Select</option>
<option value="Newport">Newport</option>
<option value="Mahdi">Mahdi</option>
<option value="Cardiff">Cardiff</option>
<option value="Cilo">Cilo is</option>
</select>
</fieldset>
<button>Save</button>
</form>

您不会在演示中看到警报,因为在片段沙盒 iframe 中不允许这样做 :(

关于javascript - 如何使用 JavaScript 验证 HTML 中的 "Select"标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33576038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com