关于前端:JQuery获取form表单数据及数据提交二

16次阅读

共计 1645 个字符,预计需要花费 5 分钟才能阅读完成。

HTML

<form action=""class="formBox">
    <input type="text" placeholder="YOUR NAME">
    <input type="text" placeholder="YOUR MAIL">
    <textarea name=""id="" placeholder="YOUR MESSAGE"></textarea>
    <input type="submit" value="Submit your email" class="tjBtn">
</form>

jQuery

var common = {
   baseSize: 100,
   init: function () {
     let that = this;
     that.bindSubmitBtn();},
  bindSubmitBtn: function () {$(document).ready(function () {$($("input.tjBtn")[0]).bind("click", function () {//  alert("Hello World bind");
            // $("form.formBox").attr("action", "#");
            $('form.formBox').submit((e) => {e.preventDefault();
            })
            // 获取第一个 input
            var userNmae = $($($("form.formBox")[0]).find("input")[0]).val();
            // 获取第二个 input
                var userEmail = $($($("form.formBox")[0]).find("input")[1]).val();
            // 获取第一个 textarea
            var usermsg = $($($("form.formBox")[0]).find("textarea")[0]).val();
            // 自定义参数名
            var param = {name: userNmae, email: userEmail, message: usermsg};
            //  用户名验证
            if (userNmae == null || userNmae == "") {alert("用户名不能为空");
                  return false;
            } else if (userNmae.length < 5 || userNmae.length > 20) {alert("用户名长度必须介于 5 -20 个字符之间!");
                  return false;
            }
            var atpos = userEmail.indexOf("@");
              var dotpos = userEmail.lastIndexOf(".");
            // 邮箱验证
            if (userEmail == "") {alert("邮箱不能为空");
                  return false;
            } else if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >=         userEmail.length) {alert("不是一个无效的 e-mail 地址");
                  return false;
            }
            // 信息验证
            if (usermsg == "") {alert("信息不能为空");
                  return false;
            }
            // 提交表单
            $.ajax({
                  type: "POST",
                  url: "https://api.trade.org/live/userinfo",
                // 传参 param
                  data: param,
                  dataType: "json",
                  success: function (respMsg) {msgpop(respMsg.msg , 3000)
                  }
            });
            // return false;
          });
    });
  },
};/**
 * 增加提醒弹框
 * msg 提醒音讯文案
 * time 提醒音讯弹窗显示时长 (单位毫秒)
 */ 
function msgpop(msg,time) {$(".popup2").after(`
        <div class='popup3'>
            <div>${msg}</div>
        </div>
      `);

      setTimeout(function () {$('.popup3').remove();},time||5000)
}

common.init();

正文完
 0