Javascript 单击文本输入时清除单选按钮

Javascript 单击文本输入时清除单选按钮,javascript,jquery,html,forms,radio,Javascript,Jquery,Html,Forms,Radio,我有一组4个单选按钮,后跟一个文本输入,当用户单击文本输入字段时,我试图清除所有单选输入。这是到目前为止我的代码 <input type="radio" name="radio"><label for="radio1">1</label> <input type="radio" name="radio"><label for="radio2">2</label> <input type="radio" name=

我有一组4个单选按钮,后跟一个文本输入,当用户单击文本输入字段时,我试图清除所有单选输入。这是到目前为止我的代码

 <input type="radio" name="radio"><label for="radio1">1</label>
 <input type="radio" name="radio"><label for="radio2">2</label>
 <input type="radio" name="radio"><label for="radio3">3</label>
 <input type="radio" name="radio"><label for="radio4">4</label>
 <input type="text" id="textInput">

 <script>
      $('#textinput').click(function () {
          radio.checked = false;
      });
 </script>
您可以使用设置输入框按钮的选中属性。此外,在事件绑定时,您还拼错了textInput

<script>
      $('#textInput').click(function () {
          $('input[name="radio"]').prop("checked", false);
      });
 </script>
您可以使用设置输入框按钮的选中属性。此外,在事件绑定时,您还拼错了textInput

<script>
      $('#textInput').click(function () {
          $('input[name="radio"]').prop("checked", false);
      });
 </script>

或者您可以尝试attr方法

 $('#textInput').click(function () {
         $('input[name="radio"]').attr('checked',false);

      });

或者您可以尝试attr方法

 $('#textInput').click(function () {
         $('input[name="radio"]').attr('checked',false);

      });

我认为在不更改html的情况下修改脚本块的最佳方法是首先确保代码在文档就绪的情况下运行,并且您可能还应该确保事件是焦点,而不是单击,以防有人使用键盘或其他导航:

$(function() {
    $('#textInput').focus(function () {
          $('input[name=radio]').prop("checked", false);
    });
});
虽然更可能的情况是,如果其他选择实际在该字段中输入了一些数据,则您只希望清除这些选择,但您可能希望执行以下操作:

$(function() {    
    $('#textInput').on('input', function () {
        if($(this).val().length > 0) {
            $('input[name=radio]').prop("checked", false);
        }
    });
});

我认为在不更改html的情况下修改脚本块的最佳方法是首先确保代码在文档就绪的情况下运行,并且您可能还应该确保事件是焦点,而不是单击,以防有人使用键盘或其他导航:

$(function() {
    $('#textInput').focus(function () {
          $('input[name=radio]').prop("checked", false);
    });
});
虽然更可能的情况是,如果其他选择实际在该字段中输入了一些数据,则您只希望清除这些选择,但您可能希望执行以下操作:

$(function() {    
    $('#textInput').on('input', function () {
        if($(this).val().length > 0) {
            $('input[name=radio]').prop("checked", false);
        }
    });
});

id应该是textInput而不是textInput capital I。@user3117555不会给所有单选按钮赋予相同的名称。每个元素的名称都应该是唯一的。如果需要对单选按钮进行分组,则需要为其指定相同的名称。否则,您将能够一次选择所有选项@i_m_选项但如果您想单独选择它们,则可以使用不同的名称。是的,但单选按钮一次只能选择一个选项:id应为textInput而不是textInput capital i。@user3117555不会给所有单选按钮赋予相同的名称。每个元素的名称都应该是唯一的。如果需要对单选按钮进行分组,则需要为其指定相同的名称。否则,您将能够一次选择所有选项@i_m_选项但如果您想单独选择它们,则可以使用不同的名称。是的,但单选按钮一次只能选择一个选项:在文本输入的初始选择器上拼写错误。但是,是的,这是有效的。这里有一个小提琴拼错了textInput的初始选择器。但是,是的,这是有效的。这是一把小提琴