javascript - 使用 Javascript 清除文本框和单选按钮 onclick

标签 javascript input radio-button textfield

<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()为了找到元素和 .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="" />

关于javascript - 使用 Javascript 清除文本框和单选按钮 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52385672/

相关文章:

javascript - AngularJS 格式化程序 - 如何显示空白而不是零

bash - 如何检查 bash 中是否有超过 5 个可供读取的输入?

java - 单选按钮选择决定下一页

javascript - Bootstrap模式提交不传递变量

javascript - 当页面重新加载时正在监视的属性未更改时,Vue watch 不会运行

javascript - 在 Webpack 中分离外部

javascript - 将参数传递给 javascript 函数时获取 [object]

javascript - 如何使搜索表单背景颜色同时悬停在输入提交和输入文本上

radio-button - Wicket RadioChoice 默认选中

php - 如何使用 PHP 将未回答的单选按钮问题作为 NULL 值发布到 MySQL 数据库中?