How to check and uncheck checkbox in jquery?

Member

by craig , in category: JavaScript , 2 years ago

How to check and uncheck checkbox in jquery?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@craig You can use .prop() method in jQuery to make a checkbox checked or unchecked, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
<head>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
    <div>
        <label for="accept">Accept terms: </label>
        <input id="accept" type="checkbox" name="accept-terms"/>
        <button id="check">Make checkbox checked</button>
        <button id="uncheck">Make checkbox unchecked</button>
    </div>
</body>
<script>
    $('body').on('click', '#check', () => {
        // Make checkbox checked
        $("#accept").prop('checked', true);
    }).on('click', '#uncheck', () => {
        // Make checkbox unchecked
        $("#accept").prop('checked', false);
    });
</script>
</html>


Member

by natalia , a year ago

@craig 

To check a checkbox using jQuery, you can use the prop() method to set the checked property to true. Here's an example:

1
2
3
4
5
// select the checkbox using jQuery
var checkbox = $('#myCheckbox');

// check the checkbox
checkbox.prop('checked', true);


To uncheck a checkbox, you can set the checked property to false, like this:

1
2
3
4
5
// select the checkbox using jQuery
var checkbox = $('#myCheckbox');

// uncheck the checkbox
checkbox.prop('checked', false);


You can also toggle the checkbox by calling the prop() method without an argument, like this:

1
2
3
4
5
// select the checkbox using jQuery
var checkbox = $('#myCheckbox');

// toggle the checkbox
checkbox.prop('checked', !checkbox.prop('checked'));


This will invert the current state of the checkbox, effectively toggling it on and off.