【收藏】8段JQuery处理表单的代码片段,很实用

时间:2023-03-09 19:16:31
【收藏】8段JQuery处理表单的代码片段,很实用

1 只接受数字输入

$("#uAge").keydown(function(event) {
// 允许退格和删除键
if ( event.keyCode == 46 || event.keyCode == 8 ) {
}
else {
// 保证输入的是数字键
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});

2 全选

$("#checkall").click(function() {
//固有属性使用prop,切记
$("#myForm input:checkbox").prop("checked",true);
});

3 反选

$("#inverse").click(function() {
$("#myForm input:checkbox").each(function () {
$(this).prop("checked",!$(this).prop("checked"))
})
});

4 单选框标签表示

//css,隐藏radio圆形,用label表示
//实际使用中,样式写的好看一些
.sex input { display: none; }
.selected { background: red; }
//javascript
$("input:radio").click(function () {
$("input:radio").parent("label").removeClass("selected");
$(this).parent("label").addClass("selected");
})

5 还可输入多少字符提示

//第一个参数:总字符数
//第二个参数:还可输入多少显示区对象
$.fn.limiter = function (limit, elem) {
$(this).on("keyup focus", function () {
setCount(this, elem);
});
function setCount(src, elem) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html(limit - chars);
}
setCount($(this)[0], elem);
}
$("#title").limiter(3,$("#limit"));

6 输入域显示缺省值

$('.default').each(function() {
var $this = $(this);
var defaultVal = $this.attr('title');
if($this.val().length ==0) {
$this.val(defaultVal);
}
$this.focus(function() {
if ($this.val() === defaultVal) {
$this.val('');
}
});
$this.blur(function() {
if ($this.val().length === 0) {
$this.val(defaultVal);
}
});
});

7 Email验证

$.fn.validateEmail = function () {
var $this = $(this);
$this.change(function () {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if ($this.val() == "") {
$this.removeClass("badEmail").removeClass("goodEmail")
} else if (reg.test($this.val()) == false) {
$this.removeClass("goodEmail");
$this.addClass("badEmail");
} else {
$this.removeClass("badEmail");
$this.addClass("goodEmail");
}
});
};

8 避免重复提交

$('form').submit(function() {
if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
jQuery.data(this, "disabledOnSubmit", { submited: true });
$('input[type=submit], input[type=button]', this).each(function() {
$(this).attr("disabled", "disabled");
});
return true;
}
else
{
return false;
}
});