javascript 如果选中单选按钮显示 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30730218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:37:46  来源:igfitidea点击:

If Radio button checked show div

javascripthideshowradio

提问by Dhawal Mhatre

I have HTML CODE below:

我有下面的 HTML 代码:

$('input[type="radio"]').click(function(){
  
  if($(this).attr("value")=="ABC"){
    $(".Box").hide('slow');
  }
  if($(this).attr("value")=="PQR"){
    $(".Box").show('slow');

  }        
});
<table>
  <tr>
    <td align="left" height="45">

      <input type="radio" class="radioBtn" name="Radio" 
             id="Radio" value="ABC" required>
      ABC

      <input class="radioBtn" type="radio" name="Radio" 
             id="Radio" value="PQR"  required>
      PQR

      <div class="Box" style="display:none">Text</div>
    </td>
  </tr>
</table>

All above code is working fine & properly. But my issue is that when I checked by default PQR then the Box div should display with clicking radio button. What wrong in my code or what changes it need..??

以上所有代码都运行良好且正常。但我的问题是,当我默认检查 PQR 时,Box div 应该通过单击单选按钮显示。我的代码有什么问题或需要什么更改..??

回答by ozil

you need to triggerthe click

你需要triggerclick

$(document).ready(function () {

    $('input[type="radio"]').click(function () {
        if ($(this).attr("value") == "ABC") {
            $(".Box").hide('slow');
        }
        if ($(this).attr("value") == "PQR") {
            $(".Box").show('slow');

        }
    });

    $('input[type="radio"]').trigger('click');  // trigger the event
});

DEMO

演示

回答by Muhammad Sufiyan

what i understood with your this statement is something like below:

我对你这个声明的理解如下:

<input class="radioBtn" type="radio" name="Radio" id="Radio" value="PQR" checked>

<input class="radioBtn" type="radio" name="Radio" id="Radio" value="PQR" checked>

means you are keeping your PQR checked by default...if so.. then below solution will work fine for you...

意味着您在默认情况下保持 PQR 处于选中状态……如果是这样……那么下面的解决方案对您来说很好用……

i am not so good is javascript but ..hope this help..

我不太擅长 javascript 但..希望这有助于..

$(document).ready(function(){

if($('input[name="Radio"]').attr("value")=="PQR"){
  $(".Box").show('slow');
}
if($('input[name="Radio"]').attr("value")=="ABC"){
  $(".Box").hide('slow');
}

$('input[type="radio"]').click(function(){
    if($(this).attr("value")=="ABC"){
        $(".Box").hide('slow');
    }
    if($(this).attr("value")=="PQR"){
        $(".Box").show('slow');

    }        
});
});