Как проверить и снять родительский и дочерний ввод с помощью jquery? - PullRequest
0 голосов
/ 18 октября 2019

В моем модуле блогов я могу назначать категории каждому блогу. В категориях могут быть дочерние категории, как показано в этом коде:

<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');

          })

        }

      });

, но он не работает должным образом для всех входов (все дочерние входы не проверены, кроме первого).

Я использую скрипт для проверки родительского ввода, если проверен один из его дочерних элементов. Чего не хватает в моем скрипте, так это если все дочерние входы не отмечены, я хочу, чтобы родительский вход был не отмечен, и, во-вторых, когда я снимаю флажок с родительского входа, я хочу, чтобы все дочерние входы не проверялись.

Ответы [ 2 ]

1 голос
/ 18 октября 2019

Может быть, есть более простые методы, но я верю, что это поможет. Ввести коды лезвий Laravel, такие как foreach и ids.

Пример: <input type="checkbox" name="page_id[]" value="1" id="parent_1" onchange="parentChanged(1)"> My Title 1

изменить на

<input type="checkbox" name="page_id[]" value="{{ $page->id }}" id="parent_{{ $page->id }}" onchange="parentChanged({{ $page->id }})"> {{ $page->title }}

function parentChanged(parent_id) {
  if ($('#parent_'+parent_id).prop("checked")) {
    $('.child_'+parent_id).prop("checked", true);
  }
  else {
    $('.child_'+parent_id).prop("checked", false);
  }
}

function childChanged(parent_id) {
  if ($(".child_" + parent_id +":checked").length > 0)
  {
      $('#parent_'+parent_id).prop("checked", true);
  }
  else
  {
     $('#parent_'+parent_id).prop("checked", false);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <tr>
    <td>
      <input type="checkbox" name="page_id[]" value="1" id="parent_1" onchange="parentChanged(1)"> My Title 1
    </td>
  </tr>

  <tr>
    <td>
      <input type="checkbox" value="1" name="idCateg[]" class="child_1" onchange="childChanged(1)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="2" name="idCateg[]" class="child_1" onchange="childChanged(1)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="3" name="idCateg[]" class="child_1" onchange="childChanged(1)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="4" name="idCateg[]" class="child_1" onchange="childChanged(1)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="5" name="idCateg[]" class="child_1" onchange="childChanged(1)"> My Category
    </td>
  </tr>
  
  
  <tr>
    <td>
      <input type="checkbox" name="page_id[]" value="1" id="parent_2" onchange="parentChanged(2)"> My Title 2
    </td>
  </tr>

  <tr>
    <td>
      <input type="checkbox" value="1" name="idCateg[]" class="child_2" onchange="childChanged(2)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="2" name="idCateg[]" class="child_2" onchange="childChanged(2)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="3" name="idCateg[]" class="child_2" onchange="childChanged(2)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="4" name="idCateg[]" class="child_2" onchange="childChanged(2)"> My Category
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" value="5" name="idCateg[]" class="child_2" onchange="childChanged(2)"> My Category
    </td>
  </tr>
</table>
1 голос
/ 18 октября 2019

Думаю, вам следует проверить, проверен ли хотя бы один дочерний элемент или нет.

Если нет, снимите флажок родительского ввода, в противном случае проверьте родительский вход:

$( '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 );
    }
} );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...