Chceking Checkbox State
To determine if a checkbox is checked:
const isChecked = $('input[type="checkbox"]').is(':checked');
This returns true if selected, otherwise false.
Retrieving Checked Checkbox Values
Collect values of all checked checkboxes with a specific name:
const selectedValues = [];
$('input[name="test"]:checked').each((index, element) => {
selectedValues.push($(element).val());
});
Checkbox Selection Controls
Implemetn common selection behaviors:
$(document).ready(() => {
$('#selectAll').on('click', () => {
$('input[name="checkbox"]').prop('checked', true);
});
$('#deselectAll').on('click', () => {
$('input[name="checkbox"]').prop('checked', false);
});
$('#selectOdd').on('click', () => {
$('input[name="checkbox"]:odd').prop('checked', true);
});
$('#toggleSelection').on('click', () => {
$('input[name="checkbox"]').each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
});
});
Getting Select Dropdown Value
Retrieve the currently selected value from a dropdown:
const selectedOption = $('#select').val();
Obtaining Selected Radio Button Value
Multiple equivalent approaches to get the value of a selected radio button:
$('input:radio:checked').val();
$('input[type="radio"]:checked').val();
$('input[name="rd"]:checked').val();
Selecting Specific Radio Buttons
Set the first radio button as selected:
$('input:radio:first').prop('checked', true);
Set the last radio button as selected:
$('input:radio:last').prop('checked', true);
Select a radio button by index (zero-based):
$('input:radio').eq(2).prop('checked', true); // selects third option
Alternatively using slice (selects second option):
$('input:radio').slice(1, 2).prop('checked', true);
Select by value:
$('input:radio[value="rd2"]').prop('checked', true);