版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyk304443164/article/details/75014679
本文出自:
http://blog.csdn.net/wyk304443164
直接上代码,使用比较简单,思想稍微复杂一点
/**
* Created by wuyakun on 2017/7/7.
*/
var cooperation = {};
cooperation.isCanSubmit = function () {
var allInputValue = common.getAllInputValue(cooperation.getAllInputId());
if (allInputValue === false) {
//设置按钮点击不了
$("#cooperation-submit").addClass("button-disabled");
} else {
//设置按钮可以点击
$("#cooperation-submit").removeClass("button-disabled");
}
};
cooperation.getAllInputId = function () {
return [{
name: 'company_name',
isMust: true
}, {
name: 'name',
isMust: true
}, {
name: 'tel_phone',
isMust: true,
judge: function (value) {
return common.isMobilePhone(value);
}
}, {
name: 'email',
isMust: false,
judge: function (value) {
return value === '' || common.isEmail(value);
}
}];
};
$(document).ready(function () {
/**
* 开始监听所有的input框
*/
function startInputListener() {
var list = cooperation.getAllInputId();
for (var i = 0; i < list.length; i++) {
var idName = '#' + list[i].name;
$(idName).bind('input propertychange', function () {
cooperation.isCanSubmit();
});
}
}
startInputListener();
//给我们亲爱的submit添加一个事件
$("#cooperation-submit").click(function () {
var listValue = common.getAllInputValue(cooperation.getAllInputId());
if (listValue) {
var postData = {
name: listValue[1],
phone: listValue[2],
companyName: listValue[0],
email: listValue[3]
};
if(listValue[0].length>20){
alert('单位名称长度不可超于20');
return;
}
if(listValue[1].length>20){
alert('联系人长度不可超于20');
return;
}
$.ajax({
url: 'http://xxx.com.cn/agent/save',
data: postData,
// contentType: 'text/plain',
contentType: 'application/x-www-form-urlencoded',
type: 'POST',
dataType: 'json'
}).done(function (result) {
if (!common.isEmpty(result) && result.success === true) {
alert('提交申请成功,我们将在一个工作日内与您取得联系');
document.location.reload();
}
});
}
});
});
/**
* 根据input id获取值
* @param id
*/
common.getInputValueById = function (id) {
var idn = '#' + id;
return $(idn)[0].value;
};
/**
* 获取所有的input框 成立就返回 list 不成立就返回false
*/
common.getAllInputValue = function (list) {
var listValue = [];
for (var i = 0; i < list.length; i++) {
var inputValue = common.getInputValueById(list[i].name);
if (list[i].isMust && common.isEmpty(inputValue) || list[i].judge && !list[i].judge(inputValue)) {
return false;
} else {
listValue[i] = inputValue;
}
}
return listValue;
};
/**
* 判断是不是手机号
* @param s
* @returns {boolean}
*/
common.isMobilePhone = function (s) {
var re = /^1[0-9]{10}$/;
return re.test(s);
};
/**
* 判断邮箱的格式
* @param y
* @returns {boolean}
*/
common.isEmail = function (y) {
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return filter.test(y);
};
/**
* 判断是不是空的或者undefined
* @param obj
* @returns {boolean}
*/
common.isNull = function (obj) {
return obj === null || typeof obj === 'undefined';
};
/**
* 判断是不是空的字符串
* @param obj
* @returns {boolean}
*/
common.isEmpty = function (obj) {
return this.isNull(obj) || obj === '';
};
ok整体比较优雅