11
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试表单获取元素值</title> <link rel="stylesheet" type="text/css" href="../bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script> <style type="text/css"> *{ margin: 0; padding: 0; } .main{ padding: 0px 15px; } input{ margin-right: 15px; display: inline-block; } </style> </head> <body> <div class="main"> <div class="row"> <label>姓名:</label><input type="text" name="name" value="" /> </div> <div class="row"> <label>多选:</label> <label for="checkbox1">多选1:</label><input type="checkbox" name="多选" id="checkbox1" value="checkbox1"> <label for="checkbox2">多选2:</label><input type="checkbox" name="多选" id="checkbox2" value="checkbox2"> <label for="checkbox3">多选3:</label><input type="checkbox" name="多选" id="checkbox3" value="checkbox3"> </div> <div class="row"> <label>下拉:</label> <select name="opt"> <option value="opt1" name="opt">下拉1</option> <option value="opt2" name="opt">下拉2</option> <option value="opt3" name="opt">下拉3</option> <option value="opt4" name="opt">下拉4</option> </select> </div> <div class="row"> <label>单选:</label> <label for="radio1">单选1:</label><input type="radio" name="radio" id="radio1" value="radio1"> <label for="radio2">单选2:</label><input type="radio" name="radio" id="radio2" value="radio2"> <label for="radio3">单选3:</label><input type="radio" name="radio" id="radio3" value="radio3"> <label for="radio4">单选4:</label><input type="radio" name="radio" id="radio4" value="radio4"> </div> <button id="submit">提交</button> </div> <script type="text/javascript"> $("#submit").on("click",function(){ //给多选框的某个选中 $(".main").find("input[name=‘多选‘]")[1].checked=true; //获取多选框选中的索引: console.log("多选框suoyin:"+$("input[name=‘多选‘]").index($("input[name=‘多选‘]:checked"))); //获取复选框选中的值: var arr=document.getElementsByName("多选"); for(var i=0;i<arr.length;i++){ if(arr[i].checked){ console.info("多选框:"+arr[i].value); } } //反选 // $(‘input[name="多选"]‘).each(function () { // $(this).prop("checked", !$(this).prop("checked")); // }); //输入框设置值 $("input[name=‘name‘]").val("wlz111") //获取输入框值: console.info("输入框:"+$("input[name=‘name‘]").val()); //将下拉框设置成某个值 $(".main").find("select[name=‘opt‘]").get(0).selectedIndex = 3; //获取下拉框值 console.log("下拉框:"+$(‘select‘).val()); //单选按钮设置值 $(".main").find("input[name=‘radio‘]")[3].checked=true; //获取单选按钮的值: console.log("单选按钮:"+$(".main").find("input[name=‘radio‘]:checked").val()); //获取单选按钮选中的索引: console.log("单选按钮suoyin:"+$("input[type=radio]").index($("input[type=radio]:checked"))); }) </script> </body> </html>