[英]restrict form submission if the hidden input field is empty
我正在嘗試在提交表單時在后台檢測地理位置,請參見下面的代碼
<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
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.