简体   繁体   English

根据另一个复选框选中/取消选中复选框

[英]check/uncheck checkbox based on another checkbox

I looked at item 4197593 How to check uncheck a checkbox based on another checkbox and copied the code from the demo to my webpage. 我查看了项目4197593如何选中取消选中基于另一个复选框的复选框,并将代码中的代码复制到我的网页。 When I open the page I get a java error - the yellow triangle bottom left hand corner. 当我打开页面时,我收到一个java错误 - 黄色三角形左下角。 The error only occurs when I add in this javascript: 只有在我添加此javascript时才会出现错误:

<script type="text/javascript">
$(document).ready(function(){    //bind event to checkbox 

  $("input[type='checkbox']").bind('click', function(){
    var $t = $(this),         
    val = $t.val(),         
    key = val.charAt(val.length-1);      
    // check if element is checked     
    if($t.val() == 'la'+key && $t.is(':checked')) {       
      $("#lists_"+key).attr('checked', true);     
    }     
    else if($t.val() == 'la'+key){       
      $("#lists_"+key).attr('checked', false);     
    }   
  }); 
}); 
</script>

I am adding this to a php page: 我将其添加到php页面:

<?php
include('header3.html');
$Fullname = $_SESSION['membername'];

include('connectdb.php');
?>
*the above javascript is added in here*
<style type="text/css">

Hope someone can help me here as I am not too bright on java. 希望有人可以在这里帮助我,因为我对java不太好。

Huh? 咦? I do not see any java in your code, only a mix of HTML and javascript . 我在你的代码中没有看到任何java ,只有HTMLjavascript的混合。

Moreover, you should learn the basics of javascript rather than copy + paste scripts. 此外,您应该学习javascript的基础知识,而不是复制+粘贴脚本。

For instance, the code you have looks like it needs the jQuery javascript library... 例如,您所拥有的代码看起来需要jQuery javascript库...

Doing what you are asking in plain javascript is as trivial as: 用普通的javascript做你正在问的事情就像这样简单:

<input type="checkbox" id="original" onchange="update()"/>
<input type="checkbox" id="other"/>

<script type="text/javascript">
    function update(){
        var original = document.getElementById('original');
        var other = document.getElementById('other');
        original.checked = other.checked;
    }
</script>

Caution 警告

You should rename function update better or even better, make use of anonymous function bound to the checkbox's change event . 您应该更好地或更好地重命名函数update ,使用绑定到复选框的change事件匿名函数

您正在使用jQuery,因此您还需要包含jQuery .js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM