Home > Web Front-end > Front-end Q&A > jquery checkbox prop not working

jquery checkbox prop not working

王林
Release: 2023-05-18 20:17:08
Original
794 people have browsed it

I recently encountered a problem when writing a web page, that is, it did not work when using jQuery's prop() method to modify the checked attribute of the check box. After some attempts and research, I finally found the solution, which I now share with you below.

First, let us take a look at the code:

<input type="checkbox" class="my-checkbox" checked>
Copy after login
$(".my-checkbox").prop("checked", false);
Copy after login

The above code seems to have no problem. We use jQuery's prop() method to change the checked attribute of the check box to false, that is, cancel selected state. However, when we run the web page in the browser, we find that the check box is still selected and the prop() method does not work.

What's going on? Actually, the problem lies with the checked attribute. The checked attribute is a DOM attribute, not an HTML attribute. When modifying DOM properties, you should use native JavaScript methods instead of jQuery's prop() method. Therefore, we need to change the prop() method to the attr() method so that the HTML attributes can be modified. The code is as follows:

$(".my-checkbox").attr("checked", false);
Copy after login

After this modification, when we run the web page again, we will find that the check box status has been changed. changed.

In addition, if we want to use prop() to modify the checked attribute, it is also possible. However, you need to change the second parameter of prop() to a string value of "true" or "false" instead of a Boolean value. The code is as follows:

$(".my-checkbox").prop("checked", "false");
Copy after login

In this way, we can successfully use the prop() method to modify the checked attribute of the check box.

To sum up, when we use jQuery's prop() method to modify DOM attributes, we should pay attention to using HTML attributes instead of DOM attributes. In addition, when using the prop() method, you can also change the second parameter to a string value to avoid the problem that Boolean values ​​cannot work in some cases. I hope this article can help you avoid similar problems and successfully complete your programming work.

The above is the detailed content of jquery checkbox prop not working. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template