使用 Javascript 清除文本框和单选按钮 onclick
Clear textbox and radio buttons onclick with 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() and .querySelector() in order to find the elemnts and .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="" />
<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() and .querySelector() in order to find the elemnts and .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="" />