清除文本框和单选按钮点击Javascript


<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text"  value="" />

所以基本上,这是我的html。我现在想做的是使用 JavaScript,而不是 jQuery,在单击单选按钮时清除文本输入字段(如果以前输入了某些内容(,并在有人单击文本字段时取消选中单选按钮。我很快找到了一个jQuery解决方案,但任务是使用JavaScript。由于我对 JS 没有太多经验,所以我无法绕过它来让它工作。

有什么想法吗? 将不胜感激。

您可以使用 .querySelectorAll(( 和 .querySelector(( 来查找 elemnts 和 .addEventListener(( 来附加事件处理程序:

document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.addEventListener('change', function(e) {
document.querySelector('#locationName').value = '';
});
});
document.querySelector('#locationName').addEventListener('input', function(e) {
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.checked=false;
});
})
<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text"  value="" />

最新更新