This article introduces js and jQuery verification of radio, checkbox, and drop-down box (select) respectively. It is shared with everyone for your reference. The specific content is as follows
(1). Let’s talk about radio first. Radio and checkbox both have the same name and multiple values. When getting the radio value, we cannot follow the ordinary text box.value method, but To determine which one is selected.
JS verification is to use getElementsByName() to get the array
js code is as follows:
<script> function test(){ var sex = document.getElementsByName("sex"); var flag = 0; for (var i=0;i<sex.length;i++) { if (sex.item(i).checked == true) { flag = 1; break; } } if (!flag) { alert("请选择性别"); } } </script> <input type="radio" name="sex" value="m">男<input type="radio" name="sex" value="f">女 <input type="button" id="btn" value="提交" onclick="test()">
It’s much simpler to use jQuery to verify. You can write less and do more, haha:
<script src="jquery-1.7.1.min.js"></script> <script> $(document).ready(function(){ $("#btn").click(function(){ if ($(":radio:checked").length == 0) { alert("你的性别未选择"); } }); }); </script> <input type="radio" name="sex" value="m">男<input type="radio" name="sex" value="f">女 <input type="button" id="btn" value="提交">
(2) Checkbox, There is really no need to talk about this, because the checkbox and radio button are exactly the same. Just change the radio in the above script to checkbox and it will be ok. !
(3) Drop-down box (select)
Use js verification, js code:
<script> function test(){ var sex = document.getElementById("sex").value; if (!sex) { alert("你的性别未选择"); } } </script> <select id="sex"> <option value="">--请选择性别--</option> <option value="m">男</option> <option value="f">女</option> </select> <input type="button" id="btn" value="提交" onclick="test()">
Validate using jQuery:
<script src="jquery-1.7.1.min.js"></script> <script> $(document).ready(function(){ $("#btn").click(function(){ if ($("#sex").val() == '') { alert("你的性别未选择"); } }); }); </script> <select id="sex"> <option value="">--请选择性别--</option> <option value="m">男</option> <option value="f">女</option> </select> <input type="button" id="btn" value="提交">
The above is the code for validating radio buttons, check boxes, and drop-down boxes with js and jquery respectively. It is introduced according to difficulty. I hope it will be helpful to everyone's learning.