带复选框的表单提交

原文地址: https://blog.csdn.net/oiu1010110/article/details/52997438

实现了:

1.选中除开表头的任何一行中的任何一项,选中该行复选框,有利于用户体验。

2.至少选中表中一项,表单提交。

html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>带复选框的表单提交 </title>
  6. <script src="../commonJqery/jquery-3.0.0.js" type="text/javascript"> </script>
  7. <style type="text/css">
  8. table {
  9. border-collapse: collapse;
  10. }
  11. td, th {
  12. width: 40px;
  13. height: 100px;
  14. border: 1px solid #000;
  15. }
  16. table tbody tr :hover {
  17. background-color: red;
  18. }
  19. table tbody tr :not( :first-child) :hover { background-color: #666;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <form action="http://www.baidu.com" id="order_shopping" name="order_shopping" method="get" onsubmit="return checkShopping();">
  25. <table id="table" class="fl">
  26. <thead>
  27. <tr>
  28. <th>商品名 </th>
  29. <th>单价 </th>
  30. <th>购买数量 </th>
  31. <th> <input id="both" type="checkbox" name="both" autocomplete="off"> </th>
  32. </tr>
  33. </thead>
  34. <tbody>
  35. <tr>
  36. <td>香蕉 </td>
  37. <td>100 </td>
  38. <td>4 </td>
  39. <td>
  40. <input type="checkbox" name="choice" autocomplete="off">
  41. </td>
  42. </tr>
  43. <tr>
  44. <td>苹果 </td>
  45. <td>100 </td>
  46. <td>5 </td>
  47. <td>
  48. <input type="checkbox" name="choice" autocomplete="off">
  49. </td>
  50. </tr>
  51. </tbody>
  52. </table>
  53. <input type="submit" id="add_shopping" value="添加购物车"/>
  54. </form>
  55. <p id="msg"> </p>
  56. </body>
  57. </html>

js:
  1. <script type="text/javascript">
  2. $( function(){
  3. //全选
  4. $( "input[name='both']").click( function(){
  5. var $isSelected = $( this).is( ":checked");
  6. for( var i = 0;i<$( "input[name='choice']").length;i++){
  7. $( "input[name='choice']")[i].checked = $isSelected;
  8. }
  9. })
  10. //选中行选中checkbox
  11. $( "#table tr").slice( 1).each( function(){
  12. var This = this;
  13. $( this).children().click( function(){
  14. $($(This).children()[ 3]).children().each( function(){
  15. if( this.type== "checkbox"){
  16. if(! this.checked){
  17. this.checked = true;
  18. } else{
  19. this.checked = false;
  20. }
  21. }
  22. });
  23. });
  24. });
  25. });
  26. // 有选中才提交
  27. function checkShopping(){
  28. $( "#msg").html( '');
  29. var $checkbox = $( "input[name='choice']");
  30. for( var i = 0 ;i<$checkbox.length;i++){
  31. if(checkObj($checkbox[i])){
  32. return true;
  33. }
  34. }
  35. if(i==$checkbox.length){
  36. $( "#msg").html( '提示:至少选择1条信息!');
  37. return false;
  38. }
  39. }
  40. function checkObj(obj){
  41. if(obj.checked){
  42. return true;
  43. } else{
  44. return false;
  45. }
  46. }
  47. </script>

猜你喜欢

转载自blog.csdn.net/justlpf/article/details/80986729