Home Web Front-end JS Tutorial Javascript implements check box selection attribute_javascript skills

Javascript implements check box selection attribute_javascript skills

May 16, 2016 pm 04:07 PM
javascript checkbox selected

Anyone who is familiar with web front-end development knows that judging whether a check box is selected is something that is often done. There are many ways to judge, but the compatibility of these methods is often ignored during the development process, and the effect is achieved. I used to use many methods as a blogger. I often found articles on Google that were bad about this or that, and I was confused later on. I happened to see a foreign blog today and thought it explained it very well. I plan to translate it into Chinese and add some of my own opinions.

If you are engaged in web development and there are check boxes in the web pages you develop, you may need to determine whether the check box is currently selected and then execute some conditional statements. There are many ways to determine whether a checkbox is checked.

Let us first take a look at how native javascript determines this attribute. In JavaScript, after you select an element, you can easily determine whether the checkbox you selected is checked through the checked attribute of the element.

Let’s look at an example. There is a checkbox on your page and the checkbox has a unique id, such as myCheckBox, as shown below:

Copy code The code is as follows:


Now we first select this element through javascript and then get its checked attribute.

Copy code The code is as follows:

Function checkCheckBox() {
If (document.getElementById('myCheckBox').checked) {
                     //change it to alert('Its Checked'); if you not working with console
console.log('Its Checked');
         } else {
console.log('No its not Checked');
}
}

As you can see, we first select the element by id and then determine its checked attribute. If the check box is selected, its value is true. If the check box is not selected, its value will be false.

If you are using jQuery and you don’t want to use native javascript to make this judgment, there are many ways:

Use is(':checked')

In this usage you will use jQuery’s is() function. The function of this function is to determine whether the selected element or element collection meets the condition parameters you pass to the function. If the conditions are met, it returns true, otherwise it returns false.

So in order to use this function, we need to select the element and then check the value of the selector:checked. This selector works for checkboxes, radio buttons and select tags.

[/code]
$('input[type="button"]').click(function () {
If ($('#myCheckBox').is(':checked')) {
                     //change it to alert('Its Checked'); if you not working with console
console.log('Its Checked');
         } else {
console.log('No its not Checked');
}
});
[/code]

Use prop()

Before jQuery 1.6, the function attr() was used to obtain the properties and attributes of elements, but it was very confusing. So after jQuery 1.6, a new function prop() is used to obtain the current property value of the element.

But before that, we first need to understand the difference between property and attributes. Attributes are some attribute values ​​​​that you set for HTML tags. This includes the class and id you set for a tag and even the initial value you set for the input box. If you do not set the attribute value in the tag but get the attribute value through attr(), undefined will occur. prop() is also used to obtain the attribute value of an element, but the obvious difference from attr() is that even if the attribute you want to obtain is not defined in the html tag, it can still correctly return the required current attribute value.

According to official recommendations: properties with two attributes of true and false, such as checked, selected or disabled, use prop(), and others use attr().

In order to intuitively reflect the difference between the two, you can change the value of the input box immediately after the page is loaded. At this time, you will find that even if the value of your input box changes, use attr() to obtain it. The property value will not change as the text changes, but the property value obtained through property() will change as the content of the text box changes.

Look at an example, here we have an input box with an initial value set and some attribute sets:

Copy code The code is as follows:


Then in the JQuery code we write:

Copy code The code is as follows:

console.log('Attribute Value is : ' $('#myTextBox').attr('value'));
console.log('Property Value is : ' $('#myTextBox').prop('value'));

We will find that the value in the input box obtained through prop() is always synchronized with the value in it, while the value in the input box obtained through attr() is always set in the html tag. value.

Copy code The code is as follows:

$('input[type="button"]').click(function () {
alert('Attribute Value is : ' $('#myTextBox').attr('value'));
alert('Property Value is : ' $('#myTextBox').prop('value'));
});

Use filter :checked

var isChecked = $('#myCheckBox:checked').length > 0;
Another method for judging the value of this attribute is to add a filter: checked when selecting elements, and then judge the attribute of the element based on the length of the obtained element. But this usage is not recommended, because when you have many groups of checkboxes on your page and use the class selector instead of the id selector, the answers you get may be wrong.

Copy code The code is as follows:

$('input[type="button"]').click(function () {
If ($('#myCheckBox:checked').length > 0 ) {
//change it to alert('Its Checked'); if you not working with console
console.log('Its Checked');
} else {
console.log('No its not Checked');
}
});

We can see that we have several methods to obtain the selected attribute of the check item. This is exactly what web developers often need to use and get confused when choosing the correct way to use it.

The above is the entire content of this article. I hope it will be helpful to everyone learning javascript.

Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Use jQuery to implement real-time updates of checkbox selected status Use jQuery to implement real-time updates of checkbox selected status Feb 23, 2024 pm 03:45 PM

Using jQuery to Real-time Update the Selected Status of Check Boxes In web development, we often encounter situations where we need to update the selected status of check boxes in real time. By using jQuery, we can easily implement the function of updating the selected status of the check box in real time. Here's how to use jQuery to accomplish this task. First, we need to prepare a simple HTML structure containing multiple checkboxes:

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles