簡體   English   中英

使用javascript獲取html形式的輸入數組字段的長度

[英]get length of input array field in html form using javascript

我需要數組長度

HTML代碼

<form action="#" method="POST" name="form1">
    <table class="table table-hover">
        <thead>
          <tr>
            <th>Name</th>
            <th>Date</th>
            <th>&nbsp;</th>
          </tr>
        </thead>
        <tbody>
            <tr id="profile_1_">
                <td><a href="http://localhost:8000/company/jobseeker/profile/1" target="_blank">Geethu</a></td>
                <td>2017-05-10 06:20:35</td>
                <td><button type="button" class="btn btn-danger btn-xs remove-profile" id="1">Remove</button></td>
                <td><input type="hidden" name="candidate[1]"></td>
                </tr>
                  <tr id="profile_2_">
                <td><a href="http://localhost:8000/company/jobseeker/profile/2" target="_blank">John</a></td>
                <td>2017-05-10 09:04:12</td>
                <td><button type="button" class="btn btn-danger btn-xs remove-profile" id="2">Remove</button></td>
                <td><input type="hidden" name="candidate[2]"></td>
            </tr>
        </tbody>            
    </table>
</form>

我想每次刪除表格行時獲取候選數組的數量。

JavaScript代碼

<script type="text/javascript">
    $(".remove-profile").click(function(){
        alert($('input[name="candidate[]"]').length);
        var id = $(this).attr('id');
        $('#profile_'+id).remove();
        getTotal();
    });

    function getTotal(){
      var count = $('input[name="candidate[]"]').length;
      var total = count * 10 ;
      $('input[name=total]').val(total);
    }
</script>

但我總是算作0。

首先將一個類添加到您的表中tbody.profile-tbody

<tbody class="profile-tbody">
   @foreach($data as $key => $item)
     ...
   @endforeach
</tbody>

接下來添加以下jQuery代碼

$(".profile-tbody").on( "click", ".remove-profile", function() {
  $('.profile-tbody tr').length;
});

由於要動態刪除元素,因此需要使用事件委托方法將事件處理程序附加到元素。 一個簡單的.click(function將不起作用。

假設<tr> (行)的數目是數組中的項目數( $item

另外,請刪除您添加的$('input[name="candidate[]"]').length您只是在檢查輸入字段(文本框)的長度,該字段甚至不存在,因此它將始終返回0 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM