Jquery Сравнить выбранные строки таблицы с флажком и сравнить столбец - PullRequest
0 голосов
/ 31 января 2020

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

$('.ApprovalForm').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    if ($(":checkbox:checked").length < 2 || $(":checkbox:checked").length > 2) {
        alert('You have to select two flights');
    } else {
        var form = $(this);
        //get all checkboxes that are selected
        var selected = $("input:checked");

        //loop through your columns
        var x = 0;
        for (var i = 1; i <= 17; i++) {
            var prev = null;
            $.each($(selected), function() {
                var curr = $(this).closest("tr").find("td").eq(i).text();
                //if at least one value is different highlight the column
                if (curr !== prev && prev !== null) {
                    x++;
                    console.log(3333);
                }
                prev = curr;

            })
        }

        console.log(x);
        if (x <= 0) {
            $("#modal-Approve").modal('show');
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
            }).done(function(response) {
                $("#MessageStatus ").val(response);
                location.reload();

            }).fail(function(data) {
                // Optionally alert the user of an error here...
                alert(data);
            });
        } else {
            alert('Selected flights are not the same, check if they are the same by using detail  button');
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table>
	<thead>
		<tr>
			<th style="display:none">id</th>
			<th>Mission</th>
			<th>First Pilot</th>
			<th>Second Pilot</th>
			<th>Aircraft</th>
			<th>No</th>

			<th style="display:none">TakeOffTime</th>
			<th style="display:none">LandingTime</th>
			<th style="display:none">Date</th>

		</tr>
	</thead>
	<tbody>
		<tr>    
			<td>test Flying</td>
			<td>Juliet</td>
			<td>Pascal</td>
			<td>boeing 42</td>
			<td>255</td>
			<td>12:45</td>
			<td>14:20</td> <!-- exclude this from the values that will  be compared -->
			<td>12/1/2020</td> <!-- exclude this too -->
			<td> <input type="checkbox" name="FlightId[]"> </td>
		</tr>
		<tr>    
			<td>test Flying</td>
			<td>Juliet</td>
			<td>Pascal</td>
			<td>boeing 42</td>
			<td>255</td>
			<td>12:45</td>
			<td>14:30</td> <!-- exclude this from the values that will  be compared -->
			<td>12/2/2020</td> <!-- exclude this too -->
			<td> <input type="checkbox" name="FlightId[]"> </td>
		</tr>
	</tbody>
</table>

, поэтому идея состоит в том, чтобы иметь возможность исключить некоторые значения td из сравнения

1 Ответ

0 голосов
/ 01 февраля 2020
  • Добавление класса 'exc_toggle' к каждому th в строке заголовка
  • Добавление прослушивателя событий для щелчка по этим классам для переключения атрибута данных "exclude"
  • Добавьте скрытую ячейку в каждую строку в tbody , чтобы количество столбцов в заголовке и tbody строк
  • было одинаковым, добавьте в форму прослушиватель события отправки для повторения через класс 'exc_toggle' и создайте индекс to_ignore для каждого data-exclude = 1
  • Пропустите сравнение, если я обнаружен в вашем индексе игнорирования

Код ниже.

HTML:

<table>
    <thead>
        <tr id="header_row">
            <th style="display:none" class="exc_toggle">id</th>
            <th class="exc_toggle">Mission</th>
            <th class="exc_toggle">First Pilot</th>
            <th class="exc_toggle">Second Pilot</th>
            <th class="exc_toggle">Aircraft</th>
            <th class="exc_toggle">No</th>

            <th class="exc_toggle">TakeOffTime</th>
            <th class="exc_toggle">LandingTime</th>
            <th class="exc_toggle">Date</th>

        </tr>
    </thead>
    <tbody>
        <tr>    
            <td style="display:none"></td>
            <td>test Flying</td>
            <td>Juliet</td>
            <td>Pascal</td>
            <td>boeing 42</td>
            <td>255</td>
            <td>12:45</td>
            <td>14:20</td> <!-- exclude this from the values that will  be compared -->
            <td>12/1/2020</td> <!-- exclude this too -->
            <td> <input type="checkbox" name="FlightId[]"> </td>
        </tr>
        <tr>    
            <td style="display:none"></td>
            <td>test Flying</td>
            <td>Juliet</td>
            <td>Pascal</td>
            <td>boeing 42</td>
            <td>255</td>
            <td>12:45</td>
            <td>14:30</td> <!-- exclude this from the values that will  be compared -->
            <td>12/2/2020</td> <!-- exclude this too -->
            <td> <input type="checkbox" name="FlightId[]"> </td>
        </tr>
    </tbody>
</table>

jQuery (в заголовке документа):

        $(document).on('click', '.exc_toggle', function(){
            if($(this).data('exclude') == 1)
            {
                $(this).data('exclude', 0);
                $(this).css('background-color', '');
            } else {
                $(this).data('exclude', 1);
                $(this).css('background-color', '#F00');
            }           
        });

jQuery (измененное событие отправки ApprovalForm):

$('.ApprovalForm').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    if ($(":checkbox:checked").length < 2 || $(":checkbox:checked").length > 2) {
        alert('You have to select two flights');
    } else {
        var ignore_indices = [];
        var cnt = 0;
        $('.exc_toggle').each(function(){
            if($(this).data('exclude') == 1)
                {ignore_indices.push(cnt);}
            cnt++;
        });

        var form = $(this);
        //get all checkboxes that are selected
        var selected = $("input:checked");

        //loop through your columns
        var x = 0;
        for (var i = 1; i <= 17; i++) {
            if(ignore_indices.indexOf(i) < 0)
            {
                var prev = null;
                $.each($(selected), function() {
                    var curr = $(this).closest("tr").find("td").eq(i).text();
                    //if at least one value is different highlight the column
                    if (curr !== prev && prev !== null) {
                        x++;
                        console.log(3333);
                    }
                    prev = curr;

                })
            } else {
                prev = null;
            }
        }

        console.log(x);
        if (x <= 0) {
            $("#modal-Approve").modal('show');
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
            }).done(function(response) {
                $("#MessageStatus ").val(response);
                location.reload();

            }).fail(function(data) {
                // Optionally alert the user of an error here...
                alert(data);
            });
        } else {
            alert('Selected flights are not the same, check if they are the same by using detail  button');
        }
    }
});

Чтобы сравнить повторяющиеся времена взлета, добавьте класс 'взлет' к каждому тд в столбце времени взлета, затем добавьте это jQuery:

        $(document).on('change', 'input:checkbox', function(){
            var takeoff = '';
            $('.takeoff').css('background-color', '');
            $('input:checked').each(function(){
                var td_target = $(this).closest('tr').find('.takeoff');
                takeoff = td_target.html();

                var matches = $('input:checked').parents('tr').find('.takeoff:contains("'+takeoff+'")');
                if(matches.length > 1)
                    {td_target.css('background-color', '#F00');}
                else
                    {td_target.css('background-color', '');}
            });
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...