简体   繁体   中英

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. When I open the page I get a java error - the yellow triangle bottom left hand corner. The error only occurs when I add in this 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
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.

Huh? I do not see any java in your code, only a mix of HTML and javascript .

Moreover, you should learn the basics of javascript rather than copy + paste scripts.

For instance, the code you have looks like it needs the jQuery javascript library...

Doing what you are asking in plain javascript is as trivial as:

<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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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