2016-02-10 44 views
2

我想隐藏一个段落,如果使用change()函数检查单选按钮但它不工作。我错过了什么?隐藏内容,如果单选按钮被选中

$(".js-rate-type").change(function(){ 
    if(this.checked){ 
     $(".js-rate-type-content").show(); 
    }else{ 
     $('.js-rate-type-content').hide(); 
    } 
}).change(); 

jsFiddle

+0

对于哪种费率类型,内容必须显示? –

+0

每日检查时应显示内容 – brunodd

回答

4

change事件处理程序,当您选择具有相同名称的另一个无线电不会被触发,所以你需要把手绑定到两个单选按钮

$('input[name="optionsRadios"]').change(function() { 
 
    $(".js-rate-type-content").toggle($('.js-rate-type').is(':checked')); 
 
}).change(); //trigger change to see changes
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="row"> 
 
    <div class="col-md-6"> 
 

 
     <form action="#"> 
 

 
     <div class="radio"> 
 
      <label> 
 
      <input type="radio" name="optionsRadios" class="js-rate-type">Daily 
 
      </label> 
 
     </div> 
 
     <div class="radio"> 
 
      <label> 
 
      <input type="radio" name="optionsRadios">Fixed 
 
      </label> 
 
     </div> 
 

 
     </form> 
 

 
     <p class="js-rate-type-content">Lorem ipsum dolor sit.</p> 
 

 

 
    </div> 
 
    </div> 
 
</div>

+0

谢谢,我试图触发使用类名称,因为我们的项目使用单选按钮的动态名称,但我能够解决它。 – brunodd

0

你需要告诉jQuery的通过将它$(document).ready(function() {});包装内运行/绑定。

$(document).ready(function() { 
    $(".js-rate-type").change(function(){ 
     if(this.checked){ 
     $(".js-rate-type-content").show(); 
     }else{ 
      $('.js-rate-type-content').hide(); 
     } 
    }).change(); //trigger change to see changes 
}) 
+0

JSFiddle:https://jsfiddle.net/2pr3xtxf/10/ – Xarus

+0

谢谢,但你能告诉我为什么吗? – brunodd

+1

当然是的 - 实际上,你已经编写了代码,但它不会运行,因为你没有告诉它。 jQuery要求如果你希望代码在用户打开页面时运行/绑定,你需要告诉它:'当文档准备就绪时,执行:' – Xarus

1

change事件绑定到input[name=optionsRadios]而不是.js-rate-type,并切换.js-rate-type-content,并检查状态为.js-rate-type

$("input[name=optionsRadios]").change(function(){ 
    var rateType=$('.js-rate-type')[0]; 
    $(".js-rate-type-content").toggle(rateType.checked); 
}).change() 
相关问题