Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Работа с checkbox в таблицах (https://javascript.ru/forum/misc/70209-rabota-s-checkbox-v-tablicakh.html)

Black_Star 20.08.2017 13:21

Работа с checkbox в таблицах
 
Добрый день уважаемые. Встала такая задача, как по нажатию на флажок в ячейке таблици сделать так, что б свое состояние меняли на противоположное все другие флажки по вертикали и по горизонтали относительно этого? Приведу пример что б было понятнее
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</head>
<body>
<table>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key" checked></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key" checked></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
</table>


<script>
  $(".key").on("click", function(){
	console.log("key");

});

</script>
</body>
</html>


Как по нажатию на первый чекбокс, сделать так что б в первом ряду были включены 123 а 4-й был выключен и при этом в первом столбце 123 были включены а 4-й выключен. Как организовать правильную выборку ?

laimas 20.08.2017 13:32

$(".key").on("change", function(){
        $(this).closest('tr').find(':checkbox').not(this).prop('checked', function() {
            return !this.checked
        });
    });

Black_Star 20.08.2017 13:54

Цитата:

Сообщение от laimas (Сообщение 462084)
$(".key").on("change", function(){
        $(this).closest('tr').find(':checkbox').not(this).prop('checked', function() {
            return !this.checked
        });
    });

По горизонтали меняет, а вот по столбцам чёт нет.

Nexus 20.08.2017 14:29

Black_Star, https://jsfiddle.net/t7p9cfy5/
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</head>
<body>
<table>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key" checked></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key" checked></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
</table>


<script>
$('.key').change(function(e){
	e.preventDefault();//Отключаю смену состояния чекбокса, сделаю это сам
  
	var $this=$(this),
  		$table=$this.parents('table'),
      index=$this.parents('th').index(),//Номер столбца
      change_property=function(){
        var $t=$(this);
	      $t.prop('checked',!$t.prop('checked'));
      };

  $this.parents('tr').find('[type="checkbox"]').each(change_property);
  $table.find('tr').each(function(){
  	$(this).find('th').eq(index).find('[type="checkbox"]').each(change_property);
  });
});
</script>
</body>
</html>

рони 20.08.2017 14:30

Black_Star,
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</head>
<body>
<table>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key" checked></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
  <tr>
    <th><input type="checkbox" name="key" class="key" checked></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
    <th><input type="checkbox" name="key" class="key"></th>
  </tr>
</table>


<script>
var thAll = $("th");
$(".key").on("click", function() {
    var th = this.parentNode,
        i = th.cellIndex,
        tr = th.parentNode;
    thAll.filter(function() {
        return this.cellIndex == i || this.parentNode == tr
    }).find(":checkbox").not(this).prop("checked", function() {
        return !this.checked
    });
    if (thAll.length == thAll.find("input:checked").length) alert("YOU WON!!!")
});
</script>
</body>
</html>

Black_Star 20.08.2017 14:34

:thanks: Всем спасибо за помощь :thanks:

Nexus 20.08.2017 14:40

Цитата:

Сообщение от рони
if (thAll.length == thAll.find("input:checked").length) alert("YOU WON!!!")

Получилось выиграть?))
По-моему это нереально.

Upd. Реально, только что убедился.

рони 20.08.2017 14:53

Цитата:

Сообщение от Nexus
Получилось выиграть?))

где то в инете есть алгоритм как выиграть, даже думать не надо, если знаешь его.

Nexus 20.08.2017 14:55

Цитата:

Сообщение от рони (Сообщение 462100)
где то в инете есть алгоритм как выиграть, даже думать не надо, если знаешь его.

Так не интересно, да и без алгоритма думать не особо нужно, тыкай и когда-нибудь победишь.

laimas 20.08.2017 15:13

Цитата:

Сообщение от Black_Star
По горизонтали меняет, а вот по столбцам чёт нет.

$(".key").on("change", function(){
        var o = $(this), t = o.closest('tr'), e = t.find(':checkbox'), i = e.index(o);
        e.not(o).add($.map(t.siblings(), function(e) {
            return $(e).find(':checkbox').eq(i)[0]
        })).prop('checked', function() {
            return !this.checked
        });
    });


Часовой пояс GMT +3, время: 07:12.