字段启用禁用javascript无法正常工作

时间:2017-01-26 20:07:42

标签: javascript jquery html ruby-on-rails ruby-on-rails-4

我有两个单选按钮,我希望根据用户在单选按钮中选择的值在我的html页面上显示一些值。

我的html文件:

<form action="">
<input type="radio" name="calenders" value="calendar_details_b2b">B2B
<br>
<input type="radio" name="calenders" value="calendar_details_b2c">B2C
</form>
<div id="calendar_details_b2c" >
   content of B2C
</div>
<div id="calendar_details_b2b">
   content of B2B
</div>

这里是JS小提琴,工作正常:https://jsfiddle.net/0b0xp5xm/9/

现在,当我更改ID时,它无效,https://jsfiddle.net/vjLnou8h/1/

修改

我已在我的rails应用程序_form.html.erb中添加了此代码,我将在new.hrml.erb页面上进行渲染。

<script    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {

  $('input[type=radio][name=calenders]').change(function () {
  $('#calendar_details_b2b').css("display","none");
  $('#calendar_details_b2c').css("display","none");
  console.log($(this).val());
  var fieldToShow = $(this).val();
  $("#" + fieldToShow).css("display","block");
  });

});
</script>

但它仍无效。

1 个答案:

答案 0 :(得分:0)

添加JQuery引用后,它就可以了。

https://jsfiddle.net/vjLnou8h/2/

&#13;
&#13;
<html>
  <head>
    <style>
      #data_Analysis,
      #study_Design {
        display: none;
      }
    </style>  
  </head>
  <body>

    <form action="">
      <input type="radio" name="calenders" value="study_Design">B2B
      <br>
      <input type="radio" name="calenders" value="data_Analysis">B2C
    </form>

    <div id="study_Design">content of B2B</div>
    <div id="data_Analysis" >content of B2C</div>


    <!-- It's generally better to put your scripts just before the <body> tag closes
         because by the time the browser gets that far, the DOM has been read. Also,
         it can speed up page load times. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>

      $('input[type=radio][name=calenders]').change(function () {
        $('#study_Design').css("display","none");
	    $('#data_Analysis').css("display","none");
	    console.log($(this).val());
	    var fieldToShow = $(this).val();
	    $("#" + fieldToShow).css("display","block");
      });
    </script>
    
  </body>
</html>
&#13;
&#13;
&#13;