2015-09-03 118 views
1

我试图根据选择单选按钮来显示隐藏图像。但似乎jQuery脚本从未激发选择变化。我的代码看起来像下面单选按钮选择更改事件不在MVC中触发

@Html.Label("Select Chart Type") 
      @Html.RadioButton("rbChartType", "1", isChecked: true) @Html.Label("Chart1") 
      @Html.RadioButton("rbChartType", "2", isChecked: false) @Html.Label("Chart2") 
<img src="@Url.Action("GetChart1")" alt="Billing Graph" class="img-responsive" id="imgChart1" /> 
     <img src="@Url.Action("GetChart2")" alt="Usage Graph" class="img-responsive" id="imgChart2" style="visibility:hidden" /> 

脚本

$(document).ready(function() { 
    $("input[name='rbChartType']").change(function() { 
     alert('hi'); 
     var selectedRadio = $("input[name='rbChartType']:checked").val(); 
     if (selectedRadio == 1) { 
      $('#imgChart1').show(); 
      $('#imgChart2').hide(); 
     } 
     else { 
      $('#imgChart1').hide(); 
      $('#imgChart2').show(); 
     } 
    }); 
}); 

我看不到我的警告射击了!

+0

在调试器控制台的任何错误? – Dandy

+0

这是回答您的问题吗? http://stackoverflow.com/questions/4202799/radio-button-change-event –

+0

@devlin,这是我已经试过的例子;我不知道我在做什么错误,但那个也没有工作!我需要在单选按钮周围有一个表单吗?我也尝试过,但它没有工作 – techspider

回答

1

首先,你不需要按名称选择单选按钮(至少不是在事件处理程序中),如果你有很多单选按钮,你可以用类名来完成。其次,如果您将元素设置为visibility:hidden,则可以使用$("imgChart2").css('visibility', 'visible');再次显示它。或者,也可以将其设置为display:none并使用show()进行显示。

试试这个:

@Html.Label("Select Chart Type") 
@Html.RadioButton("rbChartType", "1", isChecked: true) @Html.Label("Chart1") 
@Html.RadioButton("rbChartType", "2", isChecked: false) @Html.Label("Chart2") 

<img src="@Url.Action("GetChart1")" alt="Billing Graph" class="img-responsive" id="imgChart1" /> 
<img src="@Url.Action("GetChart2")" alt="Usage Graph" class="img-responsive" id="imgChart2" style="display:none" /> 

@section scripts{ 

<script type="text/javascript"> 

    $(function() { 

     $("input:radio").on("change", function() { 

      if ($(this).val() == "1") { 
       $('#imgChart1').show(); 
       $('#imgChart2').hide(); 
      } else { 
       $('#imgChart1').hide(); 
       $('#imgChart2').show(); 
      } 
     }); 

    }); 

</script> 


} 
+0

我想到了这个问题......我没有在mvc的javascript附近添加@section scripts {}。我通过“知名度”了解了这个问题。感谢您的片段。它有解决我的问题的线索! – techspider

+0

@ user2169261没问题! – brroshan

相关问题