Home > Article > Daily Programming > How to get the selected value of the checkbox in js
This article mainly introduces the implementation method of js to get the value selected by the check box.
The implementation of the js method to obtain the selected value of the check box may be difficult for novices.
Below we will give you a detailed introduction to the js method of obtaining the value selected in the check box based on specific code examples.
The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="checkbox" name="test" value="0"/>0 <input type="checkbox" name="test" value="1"/>1 <input type="checkbox" name="test" value="2"/>2 <input type="checkbox" name="test" value="3"/>3 <input type="checkbox" name="test" value="4"/>4 <input type="checkbox" name="test" value="5"/>5 <input type="checkbox" name="test" value="6"/>6 <input type="checkbox" name="test" value="7"/>7 <input type="button" onclick="jqchk()" value="提 交"/> </body> <script> function chk() { var obj = document.getElementsByName('test'); console.log(obj); var s = ''; for (var i = 0; i < obj.length; i++) { if (obj[i].checked) s += obj[i].value + ','; } alert(s == '' ? '你还没有选择任何内容!' : s); } </script> </html>
When we select multiple options and click submit, the result is as shown below:
As shown in the figure, when you click submit, the browser will prompt a pop-up window, and the content in the pop-up window is the value selected in the check box we obtained.
In the above code, we added a click event chk() to the input submit button. In chk(), we first use the getElementsByTagName method to obtain all inputs named test and assign them to an object obj. Then define a variable s, and then perform a for loop on all input boxes to determine the selected value.
Note: We can check the element through the foreground to see if the value is selected. If check is true, it represents the selected item, and if check is false, it represents the unselected item.
This article is about the js method of obtaining the selected value of the check box. In fact, the implementation idea It is also very clear and easy to understand. I hope the introduction in this article will be helpful to friends in need!
The above is the detailed content of How to get the selected value of the checkbox in js. For more information, please follow other related articles on the PHP Chinese website!