当前位置:Gxlcms > 前端框架 > 如何利用js获取form表单数据

如何利用js获取form表单数据

时间:2021-07-01 10:21:17 帮助过:7人阅读

方法如下:

1、有的时候想偷点懒,页面上有大量的表单提交数据,每次单独获取都比较麻烦。代码冗余度也比较多,因此封装了一个方法。

2、表单元素必须要有name属性,name属性是向后端提交的字段数据。

3、html代码

  1. <h3>下拉框</h3>
  2. <select name="sel" id="sel" class="query">
  3. <option value ="sel-1">sel-1</option>
  4. <option value ="sel-2">sel-2</option>
  5. </select>
  6. <h3>输入框</h3>
  7. <input type="text" name="text1" class="query" value="hello" />
  8. <input type="text" name="text2" class="query" value="word" />
  9. <h3>密码框</h3>
  10. <input type="password" name="password" class="query" value="123456" />
  11. <h3>单选框</h3>
  12. 单选1<input type="radio" name="radio" class="query" value="r1" checked />
  13. 单选2<input type="radio" name="radio" class="query" value="r2" checked/>
  14. 单选3<input type="radio" name="radio" class="query" value="r3" />
  15. <h3>复选框</h3>
  16. 复选框1<input type="checkbox" name="check" id="" class="query" value="c1" checked/>
  17. 复选框2<input type="checkbox" name="check" id="" class="query" value="c2" />
  18. 复选框3<input type="checkbox" name="check" id="" class="query" value="c3" checked/>
  19. <h3>search</h3>
  20. <input type="range" name="range" id="" class="query" value="" />
  21. <input type="color" name="color" id="" class="query" value="" />
  22. <h3>
  23. <button type="button" id="save">
  24. 提交
  25. </button>
  26. </h3>

4、此处引入了JQ库。

4.1、js代码块

使用说明:调用方法的时候传入class名称即可。

  1. // 封装方法,获取到form表单的数据。使用此方法,表单元素必须存在那么属性。
  2. //el:元素的class名称。
  3. function getParameter(el){
  4. var obj={};
  5. $(el).each(function(index,item){
  6. // 判断元素的类型
  7. if(item.type=="text" || item.type=="password" || item.type=="select-one" || item.type=="tel" ||
  8. item.type=="search" || item.type=="range" || item.type=="number" || item.type=="month" ||
  9. item.type=="email" || item.type=="datetime-local" || item.type=="datetime" || item.type=="date" ||
  10. item.type=="color"){
  11. //获取到name的值,name的值就是向后台传递的数据
  12. obj[$(this).attr("name")]=$(this).val();
  13. }else if(item.type=="checkbox"){
  14. var stamp=false;
  15. if($(this).attr("name") && !stamp){
  16. stamp=false;
  17. // 获取到复选框选中的元素
  18. var checkboxEl=$("input[name="+$(item).attr('name')+"]:checked");
  19. if(checkboxEl){
  20. var checkboxArr=[];
  21. // 取出复选框选中的值
  22. checkboxEl.each(function(idx,itm){
  23. checkboxArr.push($(itm).val());
  24. });
  25. obj[$(this).attr("name")]=checkboxArr.join(",");
  26. }
  27. }
  28. }else if(item.type=="radio"){
  29. // 获取到单选框选中的值
  30. var radio_val=$("input[name="+$(item).attr('name')+"]:checked").val();
  31. if(radio_val){
  32. obj[$(item).attr("name")]=radio_val;
  33. }
  34. }
  35. });
  36. return obj;
  37. }
  38. // 调用方法
  39. $("#save").click(function(){
  40.    var parameter=getParameter(".query");
  41.        console.log(parameter);
  42.      });

相关教程推荐:js教程

以上就是如何利用js获取form表单数据的详细内容,更多请关注Gxlcms其它相关文章!

人气教程排行