jQuery焦点文本字段检查单选按钮

问题描述 投票:1回答:1

我忙着一点形式,但现在我被困住了。

我有这个小代码:

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);
    }
 }); 

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

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

那我错了什么?

jquery input radio-button focus checked
1个回答
1
投票

你必须使用.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" />
© www.soinside.com 2019 - 2024. All rights reserved.