2016-07-06 17 views
1

我使用的數據表,以動態行添加到我的表, 我有3列,動態字符計數

  1. 指數
  2. 文本
  3. CharCount

我需要邏輯來在其各自的「CharCount」字段中實現每個「文本」列的字符計數

這裏是我的代碼 -

$(document).ready(function() { 
    var t = $('#example').DataTable(); 
    var counter = 1; 

    $('#addRow').on('click', function() { 
     t.row.add([ 
      counter, 
      '<input type="text" id=textBox'+counter+'/>', 
      '<input type="text" id=counterBox'+counter+' disabled="true"/>' 
     ]).draw(false); 

     counter++; 
    }); 

    // Automatically add a first row of data 
    $('#addRow').click(); 
}); 
<script src="https://code.jquery.com/jquery-1.12.3.js"></script> 
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> 
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> 

<button id="addRow">Add</button>  
<table id="example" class="display" cellspacing="0" width="100%"> 
    <thead> 
     <tr> 
      <th>Index</th> 
      <th>Text</th> 
      <th>CharCount</th> 
     </tr> 
    </thead> 
    <tfoot> 
     <tr> 
      <th>Index</th> 
      <th>Text</th> 
      <th>CharCount</th> 
     </tr> 
    </tfoot> 
</table> 

因此,例如,一個用戶類型的東西在文本列,
上keyUp事件使用的,我需要的字符輸入的總數,
將顯示在相應的CharCount列的文本框中。

回答

0

你可以使用jQuery .map()去遍歷所有的領域。

$(document).ready(function(){ 
 
      var t = $('#example').DataTable(); 
 
      var counter = 1; 
 
      $('#addRow').on('click', function() { 
 
       t.row.add([ 
 
        counter, 
 
        '<input type="text" id="textBox'+counter+'" />', 
 
        '<input type="text" id="counterBox'+counter+'" readonly />' 
 
       ]).draw(false); 
 

 
       counter++; 
 
      }); 
 
    
 
      $(document).on('keyup', 'input[id^=textBox]', function() { 
 
       $(this).parents('tr').find('input[id^=counterBox]').val($(this).val().length); 
 
      }); 
 

 
      // Automatically add a first row of data 
 
      $('#addRow').click(); 
 
});
<script src="https://code.jquery.com/jquery-1.12.3.js"></script> 
 
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> 
 
    
 
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> 
 
    <button id="addRow">Add</button> 
 
    <table id="example" class="display" cellspacing="0" width="100%"> 
 
     <thead> 
 
      <tr> 
 
       <th>Index</th> 
 
       <th>Text</th> 
 
       <th>CharsLeft</th> 
 
      </tr> 
 
     </thead> 
 
     <tfoot> 
 
      <tr> 
 
       <th>Index</th> 
 
       <th>Text</th> 
 
       <th>CharsLeft</th> 
 
      </tr> 
 
     </tfoot> 
 
    </table>

+0

不是真的是我想要的,我需要的CharsLeft顯示在文本列的字符數,像對文本列的keyUp事件,相應CharsLeft列會顯示總文本列中鍵入的字符數。 –

+0

我編輯了列名以避免混淆 –

+0

@AniruddhaRaje你可以檢查更新的代碼。 – Kld