Reputation: 728
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:
[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/
Upvotes: 2
Views: 8876
Reputation: 1
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>
Upvotes: 0
Reputation: 25537
The way you binding the event was wrong, Use the attribute selector like this,
$("input[name = 'sameAddress[]']").change(function () {
if (this.checked) {
alert("checked");
}
});
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.
Upvotes: 5
Reputation: 2017
Please see below Jquery function it will help you to reach solution
$('input[type="checkbox"]').change(function(){
if($(this).is(':checked')) {
alert("test");
}
});
Upvotes: 0