Check/Uncheck checkbox with JavaScript
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
How to check/uncheck a checkbox in pure JS using an onclick event?
You're having a problem because you're using an assignment operator, =
, when a comparison operator, ==
is appropriate, as a few others have said.
The following, corrected javascript should therefore work:
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if (toggleButton.checked == true) {
toggleButton.checked = false;
} else {
toggleButton.checked = true;
}
}
Actually, there's no need to ever use == true
or == false
in javascript anyway. You could simplify your code further to this:
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if (toggleButton.checked) {
toggleButton.checked = false;
} else {
toggleButton.checked = true;
}
}
Or, because of the way that the .checked
property works in javascript:
function toggleOffer() {
toggleButton.checked = !toggleButton.checked;
}
This always sets the checkbox to the opposite boolean value, which is the same as toggling it.
But I would also like to add that you could achieve this behaviour completely without javascript using label
elements.
This would be my preferred way to do this:
<div> <label for="select-time">1 mois</label> <input type="checkbox" id="select-time" checked> <label for="select-time">12 mois</label></div>
Unable to check/uncheck the checkbox
Issue(s)
Direct DOM mutation is an anti-pattern in react (it is outside react so react can't know to rerender).
The handler also doesn't access the checked
property of the onChange
event.
const { checked } = event; // <-- should be event.target
Solution
Use react state to maintain the checked status in component state.
Move the departments
data into component state.
const [departments, setDepartments] = useState(departmentsData);
Move the handleJobTitle
handler into the component. I suggest using a curried function that accepts the sector id, department name, and the job id, you'll need these to "trace" the path to the correct nested object. You don't need to worry about getting the checked
property from event.target
as you can simply invert a checked
value in state via the JobTitleID
key value.
The idea here is to shallow copy any nested state, into new object references for react, that is being updated.
const handleJobTitle = (sectorId, deptName, JobTitleID) => () => {
setDepartments((data) =>
data.map((sector) =>
sector.sectorId === sectorId
? {
...sector,
departments: sector.departments.map((dept) =>
dept.deptName === deptName
? {
...dept,
jobTitles: dept.jobTitles.map((job) =>
job.JobTitleID === JobTitleID
? {
...job,
[JobTitleID]: !job[JobTitleID]
}
: job
)
}
: dept
)
}
: sector
)
);
};
Now simply attach the handleJobTitle
to the input's onChange
handler.
<input
type="checkbox"
id={job.JobTitleID}
onChange={handleJobTitle( // <-- pass the required values
levelOne.sectorId,
levelTwo.deptName,
job.JobTitleID
)}
name={job.JobName}
checked={job[job.JobTitleID]}
/>
Check/Uncheck checkbox depend on value match
Just compare the value in your prop:
var checkVal = 'red';
var $element = $('#black');
$element.prop('checked', $element.val() === checkVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="black" id="black" checked>
<label class="form-check-label" for="black">
Black
</label>
</div>
How to check/uncheck a checkbox by clicking a div that contains it?
You can do it much shorter:
$(".tags").click(function () {
$(this).toggleClass("active inactive")
.find("input:checkbox").prop("checked",$(this).hasClass("active"))
})
.active {background-color: yellow}
.inactive {border: 1px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tags inactive" name="item1"> Item1 <input type="checkbox" name="item1"></div>
<div class="tags inactive" name="item2"> Item2 <input type="checkbox" name="item2"></div>
<div class="tags inactive" name="item3"> Item3 <input type="checkbox" name="item3"></div>
How to uncheck checkboxes using a DOM selector?
You can loop over the NodeList
and set the checked
property to false
on each checkbox.
var checkboxes = document.getElementById("factors").querySelectorAll('input[type=checkbox]');
for(const checkbox of checkboxes){
checkbox.checked = false;
}
With jQuery, you need to pass the entire NodeList
to the jQuery function, or directly pass a selector to it.
$(checkboxes).prop('checked', false);
// or
$('#factors input[type=checkbox]').prop('checked', false);
Check/uncheck input checkboxes in Isotope
About #1 and #2, just check during the event which target was changed. You can do this by accessing event.currentTarget
.
$checkboxes.change(function(event) {
After this, just add the logic:
let currentTarget = event.currentTarget;
// if all is selected, deselect others
if (currentTarget.id == "all")
$("#filters input:not(#all)").prop("checked", false);
else // remove the checked prop from all
$("#all").prop("checked",false);
// if none is checked anymore, check all
if (!$checkboxes.filter(":checked").length)
$("#all").prop("checked", true)
// your code
var filters ...
And about the 3rd one, just add the checked
property to the input field.
<label><input type="checkbox" value="*" checked id="all">Show all</label>
How to change check/uncheck listbox when click checkbox in Javascript
You where almost there. You can set disabled property on the list box with the checked value of the checkbox, prefixed with the not operator !
to reverse the value, to get the result you want.
$('#parnerCheck2').click(function() {
$('#partnerName').prop("disabled", !$(this).prop("checked"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<th scope="row">Partner</th>
<td colspan="1" style="margin-top: 4px;">
<input id="parnerCheck2" name="parnerCheck" type="checkbox" value="0" /><span>PARTNER</span>
</td>
<td>
<select id="partnerName" name="partnerName" disabled>
<option value="" selected>Choose One</option>
<option>01 - Elite</option>
</select>
</td>
</tr>
Checkbox is unchecked, but it loads as checked
The attribute for checked
is set to false
:
checked="false"
Any value in the checked
attribute, or even the presence of the checked
attribute, will mark the checkbox as checked. Remove the attribute and the default value of unchecked will be shown.
Example: the checked
attribute is completely removed.
<div class="form-check">
<label class="form-check-label">
<input onchange="inputCHKChange(this);"
type="checkbox"
class="form-check-input"
name="undefined[]"
required="">A</label>
</div>
Check and Uncheck Parent/Child Checkboxes using Jquery
Update
Added a "Check All" box in the <thead>
Added the third state called indeterminate
which is applied to a .parent
or #all
when some of their subordinate checkboxes are checked.
Assigned .child
class to the subordinate checkboxes just to make it a little easier to follow hopefully. Details are commented in the example.
// *️⃣ Code for indeterminate state - There are comments for removal
// Bind all checkboxes to the change event
$(':checkbox').on('change', checkUncheck);
function checkUncheck(e) {
// The tag the user checked/unchecked
const $this = $(this);
// Reference to the closest <tr>
const $row = $this.closest('tr');
/*
If the user clicked a .parent...
...and if it is checked...
... .find() all the <td> of $row...
...and check them all...
...otherwise uncheck them all
*/
if ($this.is('.parent')) {
if ($this.is(':checked')) {
$row.find('.child').prop('checked', true);
} else {
$row.find('.child').prop('checked', false);
}
}
/*
If the user checked/unchecked a .child...
... .makeArray() of all of $row .child and...
... if .every() <td> is .checked then check .parent
... and if .some() <td> are .checked then .parent is...
... indeterminate, otherwise uncheck .parent
*/
if ($this.is('.child')) {
$row.find('.parent').prop('indeterminate', false); //*️⃣
const chxArray = jQuery.makeArray($row.find('.child'));
let rowChecked = chxArray.every(cb => cb.checked); //*️⃣
let someChecked = chxArray.some(cb => cb.checked);
if (rowChecked) { /* if (someChecked) { */ //*️⃣
$row.find('.parent').prop('checked', true);
} else if (someChecked) {
$row.find('.parent').prop('indeterminate', true); //*️⃣
} else {
$row.find('.parent').prop('checked', false);
}
}
/*
If the user clicked #all...
...and if it is checked...
... .find() all the <td> of $tB...
...and check them all...
...otherwise uncheck them all
*/
if ($this.is('#all')) {
$('.parent').prop('indeterminate', false); //*️⃣
if ($this.is(':checked')) {
$(':checkbox').prop('checked', true);
} else {
$(':checkbox').prop('checked', false);
}
}
/*
If the user checked/unchecked a .child or .parent...
... .makeArray() of all of <td> in <tbody> and...
... if .every() <td> is checked...
... #all is checked and if .some() <td> are checked...
... then #all is indeterminate...
... otherwise uncheck #all
*/
let allArray = jQuery.makeArray($(':checkbox').not('#all'));
if (allArray.every(cb => cb.checked)) {
$('#all').prop('indeterminate', false); //*️⃣
$('#all').prop('checked', true); /* Move to: ✳️ */
} else if (allArray.some(cb => cb.checked)) {
$('#all').prop('indeterminate', true); //*️⃣ ✳️
} else {
$('#all').prop('indeterminate', false); //*️⃣
$('#all').prop('checked', false);
}
}
<table><thead><tr><th><label><input type=checkbox id=all></label><th>All Modules<th><tbody><tr><td><label><input type=checkbox class=parent name=mod[6] value=1></label><td><span>Parent Module</span><td><label><input type=checkbox class=child name=mod[7] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[8] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[9] value=1> Sub Module</label><tr><td><label><input type=checkbox class=parent name=mod[6] value=1></label><td><span>Parent Module</span><td><label><input type=checkbox class=child name=mod[7] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[8] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[9] value=1> Sub Module</label><tr><td><label><input type=checkbox class=parent name=mod[6] value=1></label><td><span>Parent Module</span><td><label><input type=checkbox class=child name=mod[7] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[8] value=1> Sub Module</label> <label><input type=checkbox class=child name=mod[9] value=1> Sub Module</label></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related Topics
Sort Array by Firstname (Alphabetically) in JavaScript
Call ASP.NET Function from JavaScript
How to Display Length of Filtered Ng-Repeat Data
Truncate Number to Two Decimal Places Without Rounding
Advantages of Createelement Over Innerhtml
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
Format Numbers in JavaScript Similar to C#
Navigator.Geolocation.Getcurrentposition Sometimes Works Sometimes Doesn'T
Replace Multiple Characters in One Replace Call
Prevent Scrolling of Parent Element When Inner Element Scroll Position Reaches Top/Bottom
How to Fix Error: Listen Eaddrinuse While Using Nodejs
How to Send a Variable Number of Arguments to a JavaScript Function
How to Format Time Since Xxx E.G. "4 Minutes Ago" Similar to Stack Exchange Sites
Cross Origin Requests Are Only Supported for Http But It's Not Cross-Domain
Adding Click Event Listener to Elements with the Same Class
What Is the Stability of the Array.Sort() Method in Different Browsers
How to Quickly and Conveniently Disable All Console.Log Statements in My Code