I currently have a table that, when clicked, checks a checkbox and changes the color of a button from grey to green. However, when the actual checkbox field is checked, the button does not change from gray to green. I am looking to see how I could make it so that it does.
Here's my current code:
$(document).ready(function() { $('.record_table tr').click(function(event) { if (event.target.type !== 'checkbox') { $(':checkbox', this).trigger('click'); $('.submit-btn').toggleClass('green'); } }); });
.green { background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="record_table"> <tr> <td id="consent"><input type="checkbox" name="opt_in" id="opt_in" value="true" /> I CONFIRM</td> <td id="consentInfo">that all of my information is accurate and consent to be called as provided above</td> </tr> </table> <div class="row"> <div class="col-lg-12"> <div class="form-group" id="space"> <label for="txt_email" id="formsLabel"></label> <input name="btn" type="submit" class="form-control submit submit-btn" id="btnSubmit" value="SUBMIT" title="submit" placeholder="SUBMIT" /> </div> </div> </div>
If the only error is:
"Uncaught ReferenceError: $ is not defined"
That means jQuery is being imported after your script, or not imported at all.
You need import jQuery library properly.
the problem is that when you trigger a click in the checkbox you also trigger a click in the tr element (because the checkbox in inside the tr element).
I make an implementation that is working here - https://codepen.io/anon/pen/OwrNqN
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$('#opt_in').trigger('click');
} else {
$('.submit-btn').toggleClass('green');
}
});
Is not the best approach, because you are triggering twice, but for sure you can work with. :)
You can also do something like this to avoid triggering the click in the tr element twice:
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
if($('#opt_in').is(':checked'))
$('#opt_in').prop('checked',false);
else
$('#opt_in').prop('checked',true);
}
$('.submit-btn').toggleClass('green');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.