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

时间:2018-08-28 08:52:47

标签: javascript html checkbox textbox clear

我是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>

2 个答案:

答案 0 :(得分:1)

要清空输入,您需要设置值而不是innerHTML。还要注意,您可以避免仅通过使用labelid属性在for标签内创建输入

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>

答案 1 :(得分:0)

您可以尝试吗?

document.getElementById('myCheck').value = "";
相关问题