如何通过jquery选中和取消选中父子输入?

问题描述 投票:0回答:1

在我的博客模块中,我可以为每个博客分配类别。类别可能具有以下代码所示的子类别:

<table class="table">
    @foreach(App\Http\Controllers\CategoriepageController::getAllPage() as $page)
        <tr class="parent">                 
            <td>
                <input type="checkbox" name="page_id[]" 
                    value="{{ $page->id }}" 
                    {{ App\Http\Controllers\ArticleController::existPageLiaison($page->id, $article->id) == 'true' ? 'checked' : '' }} 
                    class="parent"
                >
                { $page->title }}
            </td>
        </tr>

       @foreach(App\Http\Controllers\CategorieController::getCategoriesPage($page->id) as $categ)
            <tr class="child">
                <td>
                    <input type="checkbox" value="{{ $categ->id }}" 
                        name="idCateg[]" 
                        style="margin-left: 40px;" 
                        {{ App\Http\Controllers\ArticleController::existCategLiaison($categ->id, $article->id) == 'true' ? 'checked' : '' }}
                    >
                        {{ $categ->title_fr }}
                </td>
        </tr>
        @endforeach()
    @endforeach()
</table>

对于取消选中父项时取消选中子项,我尝试过此操作:

 $('.parent').on('click', ':checkbox', function() {

        if ($(this).not(':checked')) {

          var currentRow = $(this).closest('tr');

          console.log(currentRow);

          var targetedRow = currentRow.nextAll('.child').nextUntil('.parent');

            console.log(targetedRow);

          targetedRow.each(function(index,element){

            var targetedCheckbox = $(element).find(':checkbox');

            targetedCheckbox.prop('checked', false).trigger('change');

          })

        }

      });

但是它不适用于所有输入。

我正在使用脚本来检查是否选中了其中一​​个孩子的父输入。我的脚本中缺少的是是否所有孩子输入都未选中,我希望不选中父输入,而第二个是当我取消选中父输入时所有子项输入均未选中。

jquery laravel
1个回答
0
投票
我认为您应该检查是否有至少一个孩子被检查或没有。

如果没有,则取消选中父输入,否则选中父输入:

$( 'input[name="idCateg[]"]' ).on( 'click', function() { // Check if there are children checked var has_child = false; $( this ).closest( '.child' ).children( 'input' ).each( function() { if( this.value == true ) { has_child = true; } } ); // set the parent checkbox after check the children if( has_child == true ) { $( this ).closest( '.child' ).prevAll( 'tr.parent:first' ).find( 'input' ).val( true ); } else { $( this ).closest( '.child' ).prevAll( 'tr.parent:first' ).find( 'input' ).val( false ); } } );

© www.soinside.com 2019 - 2024. All rights reserved.