js 動態添加input、select等表單元素代碼

來源:互聯網
上載者:User
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>動態添加input、select等表單元素的效果</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<!--把下面代碼加到<head>與</head>之間-->
<style type="text/css教程">
body{font:12px/1.5 tahoma,arial,b8bf53,sans-serif;}
ul{margin:0;padding:0;list-style:none;}
a{margin-left:5px;color:#07f;text-decoration:none;}
a:hover{text-decoration:underline;}
input{border:1px solid #ccc;margin:2px;}
table{border-collaps教程e:collapse;border-spacing:0;}
td{margin:0;padding:10px;border:1px solid #ccc;}
</style>
<script type="text/網頁特效" src="http://www.111cn.net/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function(){
 $("#demo1").easyinsert();//最簡單的應用
 $("#demo2").easyinsert({
  name: ["demo2", "demo2"],//可以同時添加兩個(或更多),name值相同也必須分開設定,name數組的長度就是每組input的個數。type、value、maxlength、classname四種屬性,若同組組員的設定一樣,可以只設定一次。
  value: ["預設值2-1", "預設值2-2"],//可以給同組input分別設定預設值
  maxlength: 15,//每組input的maxlength都一樣,無需使用數組
  classname: ["demo2_class1", "demo2_class2"],//不用我解釋了吧
  toplimit: 5,//可以添加組數上限(預設是0,表示無上限),它是總管,so,name相當於小組組長
  initvalue: [//初始化的時候,各input的value就是歸它管,必須是數組
   ["初始值2-1", "初始值2-2"]
  ]
 });
 $("#demo3").easyinsert({
  name: "demo3",
  toplimit: 2,
  initvalue: [
   ["初始值3-1"],//必須是數組,就算每組只有一個input
   ["初始值3-2"],
   ["初始值3-3"]//小三兒,別想矇混過關,總管只允許添加兩組
  ]
 });
 $("#demo4").easyinsert({
  name: ["demo4", "demo4", "demo4", "demo4", "demo4", "demo4"],
  type: ["text", "radio", "password", "checkbox", "file", "button"],
  value: ["我是text", "我是radio", "我是password", "我是checkbox", "", "我是button"]
 });
 $("#demo5").easyinsert({//type新增custom和select
  name: ["demo5", "demo5", "demo5", "demo5"],
  type: ["custom", "text", "custom", "select"],
  value: ["<strong style="color:#ff7b0e;">科目:</strong>", "", "<strong style="color:#ff7b0e;">類型:</strong>", { '理論': '1', '技能': '2', '上機': '3' }],
  initvalue: [
   ["<strong style="color:#ff7b0e;">科目:</strong>", "初始值5-1", "<strong style="color:#ff7b0e;">類型:</strong>", { '理論a': '1', '技能a': '2', '上機a': '3' }],
   ["<strong style="color:#ff7b0e;">科目:</strong>", "初始值5-1", "<strong style="color:#ff7b0e;">類型:</strong>", { '理論b': '1', '技能b': '2', '上機b': '3' }]
  ]
 });
});
/**
 * easyinsert 4.0
 * http://ilikejquery.com/easyinsert
 *
 * @creator   wo_is神仙 <jsw0528@mrzhang.net>
 * @depend    jquery 1.4+
**/
;(function($){
 $.fn.extend({
  "easyinsert": function(o){
   o = $.extend({
    //觸發器
    clicker: null,//根據class(或id)選擇,預設.next()擷取
    //父標籤
    wrap: "li",
    name: "i-text",
    type: "text",
    value: "",
    maxlength: 20,
    classname: "i-text",
    //新增上限值
    toplimit: 0,//0表示不限制
    //初始化值,二維數組
    initvalue: null//用於修改某資料時顯示已有的資料
   }, o || {});
   var oo = {
    remove: "<a href="#nogo" class="remove">移除</a>",
    error1: "參數配置錯誤,數組的長度不一致,請檢查。",
    error2: "參數配置錯誤,每組初始化值都必須是數組,請檢查。"
   }
   //容器
   var $container = $(this);
   var allowed = true;
   //把屬性拼成數組(這步不知道是否可以最佳化?)
   var arrcfg = new array(o.name, o.type, o.value, o.maxlength, o.classname);
   //arr ==> [name, type, value, maxlength, classname]
   var arr = new array();
   $.each(arrcfg, function(i, n){
    if ( $.isarray(n) ) {
     arr[i] = n;
    } else {
     arr[i] = new array();
     if ( i === 0 ) {
      arr[0].push(n);
     }else{
      //補全各屬性數組(根據name數組長度)
      $.each(arr[0], function() {
       arr[i].push(n);
      });
     }
    }
    //判斷各屬性數組的長度是否一致
    if ( arr[i].length !== arr[0].length ) {
     allowed = false;
     $container.text(oo.error1);
    }
   });
   if ( allowed ) {
    //擷取觸發器
    var $clicker = !o.clicker ? $container.next() : $(o.clicker);
    $clicker.bind("click", function() {
     //未添加前的組數
     var len = $container.children(o.wrap).length;
     //定義一個變數,判斷是否已經達到上限
     var ismax = o.toplimit === 0 ? false : (len < o.toplimit ? false : true);
     if ( !ismax ) {//沒有達到上限才允許添加
      var $item = $("<"+ o.wrap +">").appendto( $container );
      $.each(arr[0], function(i) {
       switch ( arr[1][i] ) {
        case "select"://下拉框
         var option = "";
         $.each(arr[2][i], function(i, n) {
          option += "<option value='"+ n +"'>"+ i +"</option>";
         });
         $("<select>", {
          name: arr[0][i],
          classname: arr[4][i]
         }).append( option ).appendto( $item );
         break;
        case "custom"://自訂內容,支援html
         $item.append( arr[2][i] );
         break;
        default://預設是input
         $("<input>", {//jquery1.4新增方法
          name: arr[0][i],
          type: arr[1][i],
          value: arr[2][i],
          maxlength: arr[3][i],
          classname: arr[4][i]
         }).appendto( $item );
       }
      });
      $item = $container.children(o.wrap);
      //新組數
      len = $item.length;
      if ( len > 1 ) {
       $item.last().append(oo.remove);
       if ( len === 2 ) {//超過一組時,為第一組添加“移除”按鈕
        $item.first().append(oo.remove);
       }
      }
      $item.find(".remove").click(function(){
       //移除本組
       $(this).parent().remove();
       //統計剩下的組數
       len = $container.children(o.wrap).length;
       if ( len === 1 ) {//只剩一個的時候,把“移除”按鈕幹掉
        $container.find(".remove").remove();
       }
       //取消“移除”按鈕的預設動作
       return false;
      });
     }
     //取消觸發器的預設動作
     return false;
    });
    //初始化
    if ( $.isarray(o.initvalue) ) {//判斷初始值是否是數組(必需的)
     $.each(o.initvalue, function(i, n) {
      if ( !$.isarray(n) ) {
       $container.empty().text(oo.error2);
       return false;
      }else{
       if ( n.length !== arr[0].length ) {
        $container.empty().text(oo.error1);
        return false;
       }
      }
      var arrvalue = new array();
      //初始值替換預設值
      $.each(n, function(j, m) {
       arrvalue[j] = arr[2][j]
       arr[2][j] = m;
      });
      $clicker.click();
      //預設值替換初始值
      $.each(arrvalue, function(j, m) {
       arr[2][j] = m;
      });
      //上面這種[移形換位法]不知道效率怎麼樣,我想不出別的更好的方法
     });
    }else{
     $clicker.click();
    }
   }
  }
 });
})(jquery);
</script>
</head>
<body>
預覽效果時左下角會提示錯誤,而且看不到效果,重新整理一下就可以看到效果了;當然,在實際使用中,不會出現這樣的問題。<br>
<!--把下面代碼加到<body>與</body>之間-->
<table width="90%" align="center">
 <tr>
  <td width="10%" align="right"><strong>demo1</strong></td>
  <td width="90%">
   <ul id="demo1"></ul>
   <a href="#">+ 添加</a>
  </td>
 </tr>
 <tr>
  <td align="right"><strong>demo2</strong></td>
  <td>
   <ul id="demo2"></ul>
   <a href="#">+ 添加(最多5項)</a>
  </td>
 </tr>
 <tr>
  <td align="right"><strong>demo3</strong></td>
  <td>
   <ul id="demo3"></ul>
   <a href="#">+ 添加(最多2項)</a>
  </td>
 </tr>
 <tr>
  <td align="right"><strong>demo4</strong></td>
  <td>
   <ul id="demo4"></ul>
   <a href="#">+ 添加</a>
  </td>
 </tr>
 <tr>
  <td align="right"><strong>demo5</strong> <sup style="color:#f00;">new</sup></td>
  <td>
   <ul id="demo5"></ul>
   <a href="#">+ 添加</a>
  </td>
 </tr>
</table>
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.