我在提交表单时尝试在后台检测地理位置,请参阅下面的代码
<input type="hidden" id="f33" name="f33" value="" data-rule-required="true" readonly />
<script>
var x = document.getElementById("f33");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.value = "Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude;
}
</script>
从上面的代码我能够检测输入字段中的位置,但是,表单仍在提交,如果设备GPS关闭(作为空白字段)。
如果此输入字段为空,有没有办法限制表单提交?
尝试标记该字段required
:
<form>
<label for="choose">Would you prefer a banana or cherry?</label>
<input id="choose" name="i_like" required>
<button>Submit</button>
</form>
资料来源:https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#The_required_attribute
这取决于你如何提交表单,如果你通过Ajax(javascript)提交它,那么你可以添加if语句。如果您使用html提交它,那么您可以尝试将所需属性添加到输入,但这可能不是最佳解决方案。
这是一种通用方法
window.addEventListener("load",function() {
document.getElementById("yourFormID").addEventListener("submit",function(e) {
if (document.getElementById("f33").value.trim() === "") {
alert("Please enable your location services if present");
e.preventDefault(); // cancel submit
}
});
});