【问题标题】:If radio button is check display a textbox Jquery如果选中单选按钮,则显示文本框 Jquery
【发布时间】:2020-11-17 22:32:20
【问题描述】:

嘿,我有一个关于单选按钮的问题,我有这 3 个按钮

No <input type="radio" name="answer" checked="checked" value="no"/> 
Yes<input type="radio" name="answer" value="yes"/> 
Other <input type="radio" name="answer" value="other"/>

我也有这个文本框

<input style="display:none;" type="text" name="otherAnswer" id="otherAnswer"/>

如果用户选择值为“other”的单选按钮,则显示文本框,如果其他任何内容不显示文本框。

我对 Jquery 还很陌生,我已经查找了它的语法,但它对我来说都是希腊语。如果有人能指出我正确的方向,那就太棒了!

【问题讨论】:

    标签: jquery radio-button


    【解决方案1】:
    $("input[type='radio']").change(function(){
    
       if($(this).val()=="other")
       {
          $("#otherAnswer").show();
       }
       else
       {
           $("#otherAnswer").hide(); 
       }
    
    });
    

    这是工作示例:http://jsfiddle.net/Wc2GS/8/

    【讨论】:

      【解决方案2】:

      虽然如果您热衷于使用 jquery/javascript,上述答案就足够了,但仅使用 CSS 即可轻松实现。试试Codepen

      #otherAnswer {
          display: none;
      }
      #other:checked ~ #otherAnswer {
          display: flex;
      }
      <div>
      No<input type="radio" id="no" name="answer" checked="checked" value="no"/>
      
      Yes<input type="radio" id="yes" name="answer" value="yes"/>
      
      
      Other<input type="radio" id="other" name="answer" value="other"/> 
              
      
      <input type="text" id="otherAnswer" name="otherAnswer"/>
      </div>

      【讨论】:

        【解决方案3】:
        $(":radio").on('click',function (){
        
        if ($(this).is(":checked") && $(this).val()=='other') ) $('#otherAnswer').show(); else $('#otherAnswer').hide();
        
        });
        

        【讨论】:

        • 为什么不使用this.checkedthis.value 而不是不必要地创建jQuery 对象和调用函数?
        • @AnthonyGrist 没关系。但是因为我通常在我自己的代码中使用我的 jquery 对象 - 我会自动这样做......虽然你是对的。您可以对内部对象进行 de-jquery。
        【解决方案4】:

        我觉得这样更有效。

        $("input[name='answer']").change(function(){
        
            if($(this).val() == "yes")
            {
                $("#otherAnswer").show();
            }else{
                $("#otherAnswer").hide();
            }
        });
        

        【讨论】:

          【解决方案5】:
          $('input[name=answer]').change(function(){
              if(this.value) == 'yes'{
                  $('#otherAnswer').show();
              }else{
                  $('#otherAnswer').hide();
              }
          })
          

          【讨论】:

          • 这不能满足他们的需要;有三个带有name="answer" 的单选按钮,其中两个应确保隐藏input
          猜你喜欢
          • 2020-12-10
          • 2011-04-17
          • 1970-01-01
          • 2013-02-02
          • 2011-02-01
          • 2011-12-19
          • 2021-02-26
          • 2017-02-24
          • 2015-08-16
          相关资源
          最近更新 更多