Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Sync 2 Checkboxes

I am using the following code to sync 2 input boxes.

$("#input_box_1").bind("keyup paste", function() {
    $("#input_box_2").val($(this).val());
});

The above works great but I need to do the same for a checkbox.

My question is...how do I modify the code for it to work with a checkbox?

like image 278
Satch3000 Avatar asked Dec 16 '22 05:12

Satch3000


2 Answers

You need to modify the checked property according to the value of that property on the first checkbox whenever the first checkbox changes (so we bind to the change event):

$("#checkbox1").change(function() {
    $("#checkbox2").prop("checked", this.checked);
});

Note that you don't need to pass this into jQuery, you can just access the property of the raw DOM element, which is faster.

like image 113
James Allardice Avatar answered Jan 27 '23 09:01

James Allardice


Try something like:

$("#input_box_1").on("change", function() {
    $("#input_box_2").prop('checked', $(this).prop('checked'));
});
like image 23
Ayman Safadi Avatar answered Jan 27 '23 09:01

Ayman Safadi