ContactForm7 – Check if Checkbox is Checked

I’m stuck on how to check whether or not a checkbox has been selected using jQuery. Basically, if the checkbox is checked then I need it to run a function.

In the WordPress post, I only have to use the shortcode which is using this id:

Read More
 [contact-form-7 id="78" title="BusinessForm"]

however, it is ouputting this as the HTML:

<span class="wpcf7-form-control-wrap sameAddress">
    <span class="wpcf7-form-control wpcf7-checkbox sameAddress" id="sameAddress">
        <span class="wpcf7-list-item first last">
            <input type="checkbox" name="sameAddress[]" value="Yes">
                <span class="wpcf7-list-item-label">Yes</span>
        </span>
    </span>
 </span>

and here is the jQuery that I am using:

$(input[value='sameAddress[]']).change(function() {

    var alreadyChecked = $(this).hasClass('alreadyChecked');

    if (alreadyChecked) {
        alert('This does not have the class');  
        $(this).addClass('alreadyChecked');
    } else {
        alert('This has the class, yay!!!!! ');
    }

});

Can someone help me refine this and make it run a function/alert when the checkbox is selected? Thanks in advance.

edit: Here is a Fiddle: http://jsfiddle.net/uk3E3/

Related posts

Leave a Reply

3 comments

  1. The way you binding the event was wrong, Use the attribute selector like this,

    $("input[name = 'sameAddress[]']").change(function () {
        if (this.checked) {
            alert("checked");
        }
    });
    

    Fiddle

    In your code, there is no check box with value sameAddress[]. So it wont bind change events to any of the checkboxes.

    this.checked will return true, if the checkbox is checked.

  2. Please see below Jquery function it will help you to reach solution

    $('input[type="checkbox"]').change(function(){
        if($(this).is(':checked')) {
        alert("test");
        }
    });
    
  3. I was searching for half a day how can I use the contactform7 hiding a div – but not with select element but – with checkbox… – and the checkbox is not modified on checking, just on clicking. The checkbox value is not modified… I found this solution working (thanks to all the stackoverflow user)

    $(document).ready(function() {
    
        //Hide the field initially
        $("#hide1").hide(); 
    
        //Show the text field only when the third option is chosen - this doesn't
        $("input[name = 'programs-select1[]']").change(function () {
        if (this.checked)  {
                        $("#hide1").show();
                }
                else {
                        $("#hide1").hide();
                }
        });
    
    });
    

    The contact form 7 is looking like:

    [checkbox programs-select1 id:programs-select1 use_label_element "Week 1"]
    <div id="hide1" class="hide">
    [select* fullhalfboard-select1 id:fullhalfboard-select1 use_label_element "element1" "element2" "element3"]
    </div>