【问题标题】:Clear textbox and radio buttons onclick with Javascript使用 Javascript 清除文本框和单选按钮
【发布时间】:2019-02-22 10:28:55
【问题描述】:
<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 没有太多经验,因此我无法将其全神贯注于它的工作中。

有什么想法吗? 非常感谢。

【问题讨论】:

    标签: javascript input radio-button textfield


    【解决方案1】:

    您可以使用.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="" />

    【讨论】:

    • 非常感谢,这看起来比我所有的尝试都简单!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多