jQuery – watch a checkbox field

This is a simple function I wrote that will monitor a <checkbox> field on a form. If the <checkbox> is ticked then it will show a specified <div> and if the <checkbox> is un-ticked then it will hide the specified <div>.

View the working example

Initially I thought that I might be able to use the .toggle() function – but I when users returned to a form I needed the <div>s to show or hidden according to stored values.

I also have a very similar function that does the same thing for <select> fields. Logically you might then combine the functions into a single function or a plugin that could monitor checkboxes, radio buttons, select menus and show or hide <div>s accordingly – but at what point does the complexity of the just using the function outweigh the simplicity of using it? This is something I haven’t decide on yet.

At the moment I can just call it like so:

1
2
 
testCheckbox('id_of_checkbox', 'id_of_div');

If I were to combine these functions I would likely loose this speed / clarity – for instance a <select> might want to show or hide different <div>s based on different selected values and then I would need to start passing arrays to the function – loosing the initial simplicity. The only answer is to go ahead, write one and see what happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
<script>
   $(document).ready(function(){
 
 
 
   testCheckbox('showHide', 'targetDiv');
 
 
 
 
   function testCheckbox(key, target){
 
    if($('#'+key).is(":checked")){
     $('#'+target).show();
    }
    else {
     $('#'+target).hide();
    }
 
    $('#'+key).click( 
 
 
 
      function()
       {
 
        if($('#'+key).is(":checked"))
         {
          $('#'+target).show();
         }
        else
         {
          $('#'+target).hide();
         }
       }
     );
 
 
   }
 
   });
</script>

Note When I wrote this function it seemed logical to use the .change() function – but I have had to chnage this to .click() because .change() seems to fail silently and unpredictably in IE7.

2 Responses to “jQuery – watch a checkbox field”

  1. Njau Ndirangu

    Nice…just one question what if you have multiple checkbox that show one specific div. How do you handle it then?

  2. Flipflops

    Hi Naju

    Glad you like it – I hope it proves useful.

    If you mean that you have to separate checkboxes each of which can control the the visibility of a div, then you would just need to to call the testCheckbox() function twice e.g.

    $(document).ready(function(){
    testCheckbox(‘cb1’, ‘divToShow’);
    testCheckbox(‘cb2’, ‘divToShow’);
    });

    Of course – this means that you would probably want to tie the various checkboxes together so that if you tick one they other are ticked too – not too hard, but you would have to customize the function a bit to do so.