2014-10-07 159 views
0

我试图根据复选框的当前值,是否选中或未检查应更改文本值应向用户声明可查看文本的值。这是我所拥有的,我认为我很接近但不会工作。根据复选框值更改文本

<html> 
<body> 

<style type="text/css"> 
    .red{ display: none;} 
    .blue{ display: none;} 
</style> 

<script> 
// Toggle Text 
$(document).ready(function(){ 
     $('input[type="checkbox"]').click(function(){ 

      if($(this).attr("value")=="red"){ 
       $(".Color").toggle(); 
      }else($(this).attr("value")=="blue"){ 
       $(".Color").toggle(); 
      } 

     }); 
    }); 

</script> 

    <div> 
     <label><input type="checkbox" name="colorCheckbox" value="Color"></label> 
     </div> 

    <div class="red">You have selected <strong>red checkbox</strong></div> 
    <div class="blue">You have selected <strong>red checkbox</strong> </div> 

</body> 
</html> 
+1

又会有怎样的值更改为“红色”或“蓝色” ? – tymeJV 2014-10-07 13:09:44

+1

当jQuery运行以获取attr(“value”)时,它将获得“color” – 2014-10-07 13:10:36

回答

0

不确定你想要做什么,但我稍微修改了你的示例代码/ html。我假设你想根据连接的每一个div的显示/隐藏当某些复选框被选中:下面

$(document).ready(function(){ 
     $('input[type="checkbox"]').click(function(){ 
      if($(this).is(":checked")) 
      { 
       $("." + $(this).val()).show(); 
      } 
      else{ 
       $("." + $(this).val()).hide(); 
      } 
     }); 
    }); 

小提琴: http://jsfiddle.net/whhvks0u/4/

0

尝试为

$(document).ready(function(){ 
      $('input[type="checkbox"]').click(function(){ 
       if($(this).is(":checked")) 
       { 
       alert("checked"); 
       } 
       else{ 
       alert("Un-checked"); 
       } 
       if($(this).val()=="red"){ 
        //$(".Color").toggle(); 
       } 
       else if($(this).val()=="blue"){ 
        //$(".Color").toggle(); 
       } 

      }); 
     }); 

DEMO

0

试试这个:

$('input[type="checkbox"]').change(function(e){ 
    if ($(this).is(':checked')) { 
    $('.' + $(this).val()).toggle(); 
    } 
}); 

这是假设你的input值是一样的div类的名字之一。

0

你在找这样的吗?

<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    </head> 
    <body> 
    <style type="text/css"> 
     .red { display: none;} 
     .blue { display: none;} 
    </style> 
    <script> 
     $(document).ready(function(){ 
      $('input[type="checkbox"]').click(function(){ 

       $(".color").each(function(){ 
        $(this).hide(); 
       }); 

       if($(this).is(":checked")){ 
        var color = $(this).attr("value"); 
        $("."+color).show(); 
       } 

      }); 
     }); 
    </script> 
    <div> 
     <input type="checkbox" name="colorCheckbox" value="red"> red 
     <input type="checkbox" name="colorCheckbox" value="blue"> blue 
    </div> 
    <div class="color red">You have selected <strong>red checkbox</strong></div> 
    <div class="color blue">You have selected <strong>blue checkbox</strong> </div> 
    </body> 
</html>