---
title: "(转)10个超棒jQuery表单操作代码片段"
author: "panzertank"
date: "2012-11-30T20:05:52Z"
tags: []
categories: ["Web前端"]
slug: "10-jquery"
draft: false
lastmod: "2012-11-30T20:05:52Z"
id: 1739192
url: "https://panzertank.iteye.com/blog/1739192"
---

(转)http://www.qianduan.net/10-awesome-jquery-form-action-code-fragment-not-to-be-missed.html

 

jQuery绝对是一个伟大的开源javascript类库，是帮助我们快速和高效开发前端应用的利器。可能大家在日常的开发过程中常常会处理表单相关的javascript，在今天这篇代码片段分享文章中，这里收集了10个超棒超实用的jQuery表单处理代码，希望能够在大家的开发过程中帮助大家更好更快的处理表单相关问题，希望大家喜欢！如果你也有相关的代码，请大家积极分享！

## 代码片段1: 在表单中禁用“回车键”

大家可能在表单的操作中需要防止用户意外的提交表单，那么下面这段代码肯定非常有帮助：

[在线调试](http://www.gbin1.com/gb/debug/bc1d5165-d952-4f60-80cf-01609df7c256.htm "代码1")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code1.html "demo")

```
1
2
3
4
5
```

```
$("#form").keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});
```

## 代码片段2: 清除所有的表单数据

可能针对不同的表单形式，你需要调用不同类型的清楚方法，不过使用下面这个现成方法，绝对能让你省不少功夫。

[在线调试](http://www.gbin1.com/gb/debug/796c8b47-198c-41fe-bbc0-2add95b0f1f3.htm "代码2")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code2.html "demo")

```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
```

```
function clearForm(form) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};
```

## 代码片段3: 将表单中的按钮禁用

下面的代码对于ajax操作非常有用，你可以有效的避免用户多次提交数据，个人也经常使用：

[在线调试](http://www.gbin1.com/gb/debug/acafc73f-38ef-4ee5-8531-91e1914c9c33.htm "代码3")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code3.html "demo")

禁用按钮：

```
1
```

```
$("#somebutton").attr("disabled", true);
```

启动按钮：

```
1
```

```
$("#submit-button").removeAttr("disabled");
```

可能大家往往会使用.attr(‘disabled’,false);，不过这是不正确的调用。

## 代码片段4: 输入内容后启用递交按钮

这个代码和上面类似，都属于帮助用户控制表单递交按钮。使用这段代码后，递交按钮只有在用户输入指定内容后才可以启动。

[在线调试](http://www.gbin1.com/gb/debug/e21e22a3-6505-4c33-b30e-e92bca6fd21c.htm "代码4")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code4.html "demo")

```
1
2
3
```

```
$('#username').keyup(function() {
    $('#submit').attr('disabled', !$('#username').val()); 
});
```

## 代码片段5: 禁止多次递交表单

多次递交表单对于web应用来说是个比较头疼的问题，下面的代码能够很好的帮助你解决这个问题：

[在线调试](http://www.gbin1.com/gb/debug/c9f023bc-4048-4d1a-bc79-cd36bc818ae4.htm "代码5")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code5.html "demo")

```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
```

```
$(document).ready(function() {
  $('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;
    }
  });
});
```

## 代码片段6: 高亮显示目前聚焦的输入框标示

有时候你需要提示用户目前操作的输入框，你可以使用下面代码高亮显示标示：

[在线调试](http://www.gbin1.com/gb/debug/cb672573-0002-4b1a-9976-0116fa6f106f.htm "代码6")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code6.html "demo")

```
1
2
3
4
5
```

```
$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});
```

## 代码片段7: 动态方式添加表单元素

这个方法可以帮助你动态的添加表单中的元素，比如，input等：

[在线调试](http://www.gbin1.com/gb/debug/be24174b-08a6-4029-826e-5c5f80d5d8ff.htm "代码6")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code7.html "demo")

```
1
2
3
4
5
```

```
//change event on password1 field to prompt new input
$('#password1').change(function() {
        //dynamically create new input and insert after password1
        $("#password1").append("&amp;lt;input type='text' name='password2' id='password2' /&amp;gt;");
});
```

## 代码片段8: 自动将数据导入selectbox中

下面代码能够使用ajax数据自动生成选择框的内容

[在线调试](http://www.gbin1.com/gb/debug/1ffcde94-f05c-4dbd-828b-e8533781c08c.htm "代码8")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code8.html "demo")

```
1
2
3
4
5
6
7
8
9
10
11
```

```
$(function(){
  $("select#ctlJob").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i &amp;lt; j.length; i++) {
        options += '&amp;lt;option value="' + j[i].optionValue + '"&amp;gt;' + j[i].optionDisplay + '&amp;lt;/option&amp;gt;';
      }
      $("select#ctlPerson").html(options);
    })
  })
})
```

## 代码片段9: 判断一个复选框是否被选中

代码很简单，如下：

[在线调试](http://www.gbin1.com/gb/debug/81a81e0f-6f64-469c-ad1c-3a761edf090c.htm "代码10")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code9.html "demo")

```
1
```

```
$('#checkBox').attr('checked');
```

## 代码片段10: 使用代码来递交表单

代码很简单，如下：

[在线调试](http://www.gbin1.com/gb/debug/81a81e0f-6f64-469c-ad1c-3a761edf090c.htm "代码10")  [在线演示](http://www.gbin1.com/gb/networks/uploads/b7819361-e872-4502-8697-9d727ffb603a/code9.html "demo")

```
1
```

```
$("#myform").submit();
```

希望大家觉得这些jQuery代码会对你的开发有帮助，如果你也有类似的代码，请和我们分享！

来源：[不可错过的10个超棒jQuery表单操作代码片段](http://223.4.150.152/technology/jquery/20121127-jquery-code-for-forms/)