简体   繁体   English

使用javascript获取html形式的输入数组字段的长度

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

I need the array length 我需要数组长度

html code 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>

I want to get the count of candidate array each time i remove a table row. 我想每次删除表格行时获取候选数组的数量。

javascript code 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>

but I'am getting count as 0 always. 但我总是算作0。

Firstly add a class to your table tbody say .profile-tbody 首先将一个类添加到您的表中tbody.profile-tbody

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

Next add the following jQuery code 接下来添加以下jQuery代码

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

Since you're removing elements dynamically, you need to use the event delegation approach to attach an event handler to the element. 由于要动态删除元素,因此需要使用事件委托方法将事件处理程序附加到元素。 A simple .click(function would not work. 一个简单的.click(function将不起作用。

Assuming the number of <tr> (rows) are the number of items( $item ) in your array 假设<tr> (行)的数目是数组中的项目数( $item

Also please remove the $('input[name="candidate[]"]').length you have added, you are just checking the length of a input field(textbox) which is not even present & hence it will always return 0. 另外,请删除您添加的$('input[name="candidate[]"]').length您只是在检查输入字段(文本框)的长度,该字段甚至不存在,因此它将始终返回0 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM