davec
davec

Reputation: 1

Show/hide div when checkbox is selected

I would like to show/hide a div when a single checkbox is selected. It currently works with "Select all" but I can't get it to work with a single checkbox. Here's the code for "Select All":

JS:

<script language='JavaScript'> 
var checkboxcount = 1;

function doCheckOne() {
    if(checkboxcount == 0) {
        with (document.messageform) {
            for (var i=0; i < elements.length; i++) {
                if (elements[i].type == 'checkbox') {
                    elements[i].checked = false;
                document.getElementById('mail_delete_button').style.display = "none";
                }
            }
            checkboxcount = checkboxcount + 1;
        }
    } else
    with (document.messageform) {
        for (var i=0; i < elements.length; i++) {
            if (elements[i].type == 'checkbox') {
                elements[i].checked = true;
            document.getElementById('mail_delete_button').style.display = "block";
            }
        }
    checkboxcount = checkboxcount - 1;
    }
}
</script>

HTML:

<a href="javascript:void(0);" onclick="doCheckAll();this.blur();">Select all</a>
<div id="mail_delete_button" style="display: none;"></div>

I'd like to display the div "mail_delete_button" when a single checkbox is selected and hide it when there's nothing checked. Note: My html/input field is in the form "messageform" This is my input code:

<input type='checkbox' name='delete_convos[]' value='{$pms[pm_loop].pmconvo_id}'>

Any help would be greatly appreciated! Thanks! :)

Upvotes: 0

Views: 6137

Answers (2)

thomas
thomas

Reputation: 915

This may help someone using jQuery. You can show and hide div blocks based on the checked checkbox using jQuery’s toggle() method. The div blocks in the following example are hidden by default using the CSS display property, which is set to none.

  $(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
      var val = $(this).attr("value");
      $("." + val).toggle();
    });
  });

You can see an example here: How to show/hide DIV if checkbox selected

Upvotes: 0

sachleen
sachleen

Reputation: 31131

Something like this? Gave the checkbox an id="chk"

<input type='checkbox' name='delete_convos[]' value='{$pms[pm_loop].pmconvo_id}' id="chk">

document.getElementById("chk").onclick = function() {
    document.getElementById('mail_delete_button').style.display = this.checked ? "block" : "none";
}​

DEMO

Upvotes: 1

Related Questions