项目中 用到了jquery的clone方法 使得出现很多歌name一样的文本框
数据验证用的jquery validate 这样就造成只能验证第一个文本框的情况
网上看了下 各个好的解决方案 亲身实践 优化后 总结如下:
//这个代码必须要引用
$(function(){
if ($.validator) {
$.validator.prototype.elements = function () {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
//注释这行代码
// select only the first element for each name, and only those with rules specified
//if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
// return false;
//}
rulesCache[this.name] = true;
return true;
});
}
}
//下面是表单验证规则 根据自己 项目属性进行更改
$("#formorders").validate();
$("[name=quantity]").each(function(){
$(this).rules("add", {
required: true,
digits:true,
messages: {
required: "数量不能为空",
digits:"请输入整数"
}
});
});
$("[name=descriptionstr]").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "描述不能为空"
}
});
});
$("[name=price]").each(function(){
$(this).rules("add", {
required: true,
// regex: "^\d+(\.\d{2})?$" ,
number:true,
messages: {
required: "价格不能为空",
number:"请输入正确的价格格式"
}
});
// $(this).rules("add", { regex: "^\d+(\.\d{2})?$" })
});
// $("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"数据格式错误."
);
$("[name=loadingPort]").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "请选择起运港"
}
});
});
$("[name=destinationPort]").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "请选择目地港"
}
});
});
$("[name=paymentMethod]").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "请选择支付方式"
}
});
});
$("[name=seller]").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "请选择供应商"
}
});
});
});
然后在克隆 方法里 增加动态修改id值得方法
$(".addProd").click(function() {
$("#clone").clone(true).insertAfter("#clone");
var idstr=0;
$("[name=quantity]").each(function(){
$(this).attr("id","quantity"+idstr);
idstr++;
});
var id_descriptionstr=0;
$("[name=descriptionstr]").each(function(){
$(this).attr("id","descriptionstr"+id_descriptionstr);
id_descriptionstr++;
});
var id_price=0;
$("[name=price]").each(function(){
$(this).attr("id","price"+id_price);
id_price++;
});
})
按钮用
创建订单 这种
文本框 随意 比如:
引用
这两个js即可