Detailed explanation of attr() and prop() for selecting and canceling checkbox

小云云
Release: 2023-03-21 18:20:01
Original
3324 people have browsed it

This article mainly shares with you the detailed explanation of attr() and prop() for selecting and canceling checkbox. First of all, it must be clear that whether the CheckBox is checked has no direct relationship with whether the checked attribute of the input is =="checked".

An input without written related js function: checked, you can only control whether it is selected, as shown in the figure above.

$('.modal-body input:checked')
Copy after login

As shown in the above code, this jquery selector can find the second input, but the fact that it can be found has nothing to do with its attitude: checked.

If you want to control the checked attitude by whether it is checked, you need to add the following code:

			$('.modal-body thead').on('click','input',function(){
				if($(this).attr('checked')=='checked'){
					$(this).removeAttr("checked");
				}else{
					$(this).attr("checked", "true");
				}
			});
Copy after login

If you also want to control the events of other dom elements, whether it is checked and attitude, then you need Add the following code:

			$('.modal-body thead').on('change','select',function(){
				
				$(this).parent().find('th input').prop('checked','checked');
				$(this).parent().find('th input').attr('checked','checked');
			});
Copy after login

The prop function is used to control whether it is selected. If not used, the input element will not be selected, but the attitude value will change.

In fact, you don’t actually need to care about the checked attitude, because the jquery selector cares about whether it is selected, not the value of attitude.

But when you need to use events from other dom elements to trigger the CheckBox to be selected, you need to use the prop function. Because the user cares about vision, not the value of attitude through the console.
Related recommendations:

Style modification of input checkbox checkbox

Use of checkbox in jQuery

Use js to get the value of the checkbox

The above is the detailed content of Detailed explanation of attr() and prop() for selecting and canceling checkbox. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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