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:

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.



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 thoughts to “jQuery – watch a checkbox field”

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

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

Comments are closed.