``````javascript$(".my-checkb"/> ``````javascript$(".my-checkb">

Home  >  Article  >  Web Front-end  >  jquery checkbox prop not working

jquery checkbox prop not working

王林
王林Original
2023-05-18 20:17:08760browse

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>
$(".my-checkbox").prop("checked", false);

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);

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");

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!

Statement:
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