如何在取消选中复选框后清除文本框而不会文本框消失(JavaScript)



我是HTML,CSS和JavaScript的新手,所以请耐心等待。

我正在尝试创建一个表单,该表单具有一个元素,当用户选中复选框时,该元素使用地理位置来获取用户的当前位置,并在我设置的文本框中输入坐标。这工作正常,但是当我取消选中复选框时,坐标会随着文本框一起消失。

如何在不使文本框消失的情况下仅清除坐标?

下面是我的代码:

function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation disabled or unavailable.";
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
} else {
x.innerHTML = "";
}
}
<h4> Coordinates: <label id="place"><input type="text"></label><label>Use current location? <input id="myCheck" onclick="getLocation(this)" type="checkbox"></label>
</h4>

要清空输入,您需要设置值而不是innerHTML。另请注意,您可以通过仅使用id&for属性来避免在label标签中创建输入

function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation disabled or unavailable.";
}
} else {
x.value = "";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
<h4> Coordinates: <label for="place">
<input id ="place" type="text"></label>
<label for="myCheck">Use current location?
<input id="myCheck" onclick="getLocation(this)" type="checkbox">
</label>
</h4>

你能试试吗?

document.getElementById('myCheck').value = "";

最新更新