代码之家  ›  专栏  ›  技术社区  ›  Maanstraat

jQuery focus textfield check单选按钮

  •  1
  • Maanstraat  · 技术社区  · 8 年前

    我正忙着做一个小表格,但我现在卡住了。

    我有一个小代码:

    jQuery('#textinput input').click(function() {
        if (jQuery(this).is(':focus')) {
            jQuery('input:radio[name=open_amount]').attr('checked',true);
        } else { 
            jQuery('input:radio[name=open_amount]').attr('checked',false);
        }
     }); 
    

    这是工作的一半。当我在输入文本中键入某些内容时,将选中该单选按钮,但如果我改变主意并选中其他单选按钮,则不会在HTML代码中删除该检查。

    当我输入一个值时,改变主意,检查另一个单选按钮,然后返回到输入文本单选按钮不会自动更改。

    那么我错在哪里呢?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Eddie    8 年前

    你必须使用 .focus .blur 而不是 .click

    您还必须使用 .prop 设置收音机btn

    jQuery(function() {
    
      jQuery('#textinput input').focus(function() {
        jQuery('input:radio[name=open_amount]').prop('checked', true);
      });
    
      jQuery('#textinput input').blur(function() {
        jQuery('input:radio[name=open_amount]').prop('checked', false);
      });
    
      //Suggestion: You can add this so that when user clicks on the radio btn, it will fucos on the textbox
      jQuery('input:radio[name=open_amount]').click(function(){
        jQuery('#textinput input').focus();
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="textinput">
      <input type="text">
    </div>
    
    <input type="radio" name="open_amount" />