Checkboxes expose boolean state through the DOM checked property, so use jQuery .prop("checked") to read or change that state.
const checked =
$( "#ckb" ).prop( "checked" );
$( "#ckb" ).on( "change", function () {
const checked =
$( this ).prop( "checked" );
console.log( checked );
});
$( "#ckb" ).on( "change", function () {
$( "#ckb2" ).prop(
"checked",
$( this ).prop( "checked" )
);
});
<input type="checkbox"
id="abc"
name="ckb"
data-month-name="jun"
data-equipment-id="abc691">
$( 'input[type="checkbox"]' )
.on( "change", function () {
const id = this.id;
const name = this.name;
const checked =
$( this ).prop( "checked" );
const monthName =
$( this ).data( "month-name" );
console.log(
id,
name,
checked,
monthName
);
});
$( "#ckb" ).on( "change", function () {
$( "#ckb2" ).prop(
"disabled",
$( this ).prop( "checked" )
);
});
$( 'input[type="checkbox"]' )
.on( "change", function () {
const id = this.id;
const value = $( this ).val();
const checked =
$( this ).prop( "checked" );
$( "#msg_display" ).text(
"id: " + id +
", value: " + value +
", checked: " + checked
);
});
const values = $(
'input[type="checkbox"]:checked'
).map(function () {
return this.value;
}).get();
$( "#display" ).text(
values.join( ", " )
);
const totalChecked =
$( ".ckb:checkbox:checked" ).length;
You can also filter by a custom data attribute:
const totalChecked = $(
':checkbox:checked[data-id="my_id"]'
).length;
$( 'input[type="checkbox"]' )
.on( "change", function () {
const total = $(
'input[type="checkbox"]:checked'
).length;
if ( total > 2 ) {
$( this ).prop( "checked", false );
$( "#display" ).text(
"You have reached your maximum limit."
);
}
});
$( "#ckb5" ).on( "change", function () {
const checked =
$( this ).prop( "checked" );
$( ".group-checkbox" ).prop(
"checked",
checked
);
});
These original tutorial/demo routes are retained so no useful learner path is lost:
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| felix | 27-09-2017 |
| Great tutorial | |