Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Jquery и автоматическое выключение чекбоксов при нажатие на любой другой (https://javascript.ru/forum/jquery/79487-jquery-i-avtomaticheskoe-vyklyuchenie-chekboksov-pri-nazhatie-na-lyubojj-drugojj.html)

savsoft 15.02.2020 06:10

Jquery и автоматическое выключение чекбоксов при нажатие на любой другой
 
<!DOCTYPE html>
<html>
<head>
	<title>Товары</title>
    <meta charset="utf-8">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
	<script>
		jQuery(function ($) {

			$(document).on('change', 'input:checkbox', function () {
				
				//if (this.checked) {
				if ($(this).is(':checked')) {
				
					var myClass = this.className;
													
					$("." + myClass).not(this).prop('checked', false);
				}
				
			});
		});
	</script>
</head>
 
<body>
    	
    <div class="container-fluid">
	
		<form id="#form_goods" name="form_gooods" method="post" action="">
		
			<div class="row">
				<table class="table table-striped table-bordered" id="tgoods">
					<thead>
						<tr>
							<th>Наименование</th>						
							<th style="text-align: center;">ПН</th>
							<th style="text-align: center;">ВТ</th>
							<th style="text-align: center;">СР</th>
							<th style="text-align: center;">ЧТ</th>
							<th style="text-align: center;">ПТ</th>
						</tr>
					</thead>
					<tbody> 
						<tr id="1">
							<td>Пирог балканский</td>
							<td style="text-align: center;">
								<input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[1][1]" value="*"></td>
							<td style="text-align: center;">
								<input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[1][2]" value="*"></td>
							<td style="text-align: center;">
								<input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[1][3]" value="*"></td>
							<td style="text-align: center;">
								<input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[1][4]" value="*"></td>
							<td style="text-align: center;">
								<input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[1][5]" value="*"></td>
						</tr>		
						
						<tr id="2">
							<td>Пирог с сыром</td>
							<td style="text-align: center;">
								<input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[2][1]" value="*"></td>
							<td style="text-align: center;">
								<input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[2][2]" value="*"></td>
							<td style="text-align: center;">
								<input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[2][3]" value="*"></td>
							<td style="text-align: center;">
								<input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[2][4]" value="*"></td>
							<td style="text-align: center;">
								<input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[2][5]" value="*"></td>
						</tr>		

						<tr id="3">
							<td>Пирог с вареньем</td>
							<td style="text-align: center;">
								<input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[3][1]" value="*"></td>
							<td style="text-align: center;">
								<input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[3][2]" value="*"></td>
							<td style="text-align: center;">
								<input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[3][3]" value="*"></td>
							<td style="text-align: center;">
								<input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[3][4]" value="*"></td>
							<td style="text-align: center;">
								<input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[3][5]" value="*"></td>
						</tr>		
						
					</tbody>
				</table>
			</div>	
		</form>		
	</div> <!-- /container -->
	  
</body>
</html>

laimas 15.02.2020 07:00

$(this).closest('tr').find(':checkbox').not(this).prop('checked', this.checked)

savsoft 15.02.2020 07:08

Цитата:

Сообщение от laimas (Сообщение 520149)
$(this).closest('tr').find(':checkbox').not(this).prop('checked', this.checked)

Это вместо этих строк

var myClass = this.className;
$("." + myClass).not(this).prop('checked', false);


И какие проблемы могут быть с моим примером?

рони 15.02.2020 08:26

savsoft,
тег run добавьте в свой код.


[html run]
... минимальный код страницы с вашей проблемой
[/html]

О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

savsoft 15.02.2020 09:08

Цитата:

Сообщение от рони (Сообщение 520151)
savsoft,
тег run добавьте в свой код.

[html run]
... минимальный код страницы с вашей проблемой
[/html]

Сделал, вроде работает как нужно, но непонятно какие могут быть проблемы. Вопрос чисто по коду jquery

jQuery(function ($) {

	$(document).on('change', 'input:checkbox', function () {
				
		if ($(this).is(':checked')) {
				
			var myClass = this.className;
												
			$("." + myClass).not(this).prop('checked', false);
		}
				
	});
});


Он работает и я понимаю, что он делает. А вот предложенный другой вариант ставит меня в тупик. Собственно вопрос, мой код будет работать или нет?

И как работает предложенный вариант

$(this).closest('tr').find(':checkbox').not(this).prop('checked', this.checked)


Как он снимает отметку чекбокса в колонке таблицы, в другой строке?

рони 15.02.2020 09:16

savsoft,
проблем никаких, за исключением дополнительной установки классов, когда есть индексы.

savsoft 15.02.2020 09:21

Цитата:

Сообщение от рони (Сообщение 520153)
savsoft,
проблем никаких, за исключением дополнительной установки классов, когда есть индексы.

Хорошо, но как работает этот код

$(this).closest('tr').find(':checkbox').not(this).prop('checked', this.checked)


Я не понимаю, он что, находит блишайшую строку, находит в ней чекбокс, а если в ней не было отметки?

laimas 15.02.2020 09:42

Цитата:

Сообщение от savsoft
как работает этот код

$(this) //взять этот флажок, а это флажок Все
.closest('tr') //найти родителя всей группы флажков
.find(':checkbox') //получить все флажки группы
.not(this) //исключить из набора флажок Все
.prop('checked', this.checked) //установить всей группе состояние флажка Все


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

рони 15.02.2020 10:05

laimas,
нужны checkbox в колонке, а не все

рони 15.02.2020 10:06

savsoft,
<!DOCTYPE html>
<html>
<head>
    <title>Товары</title>
    <meta charset="utf-8">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <script>
        jQuery(function ($) {
            $('#tgoods').on('change', 'input:checkbox', function () {
                var {cellIndex : i} = this.parentNode;
                var sel = `#tgoods tbody  tr  td:nth-child(${++i}) input`;
                $(sel).not(this).prop('checked', false);
            });
        });
    </script>
</head>
<body>
    <div class="container-fluid">
        <form id="#form_goods" name="form_gooods" method="post" action="">
            <div class="row">
                <table class="table table-striped table-bordered" id="tgoods">
                    <thead>
                        <tr>
                            <th>Наименование</th>
                            <th style="text-align: center;">ПН</th>
                            <th style="text-align: center;">ВТ</th>
                            <th style="text-align: center;">СР</th>
                            <th style="text-align: center;">ЧТ</th>
                            <th style="text-align: center;">ПТ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr id="1">
                            <td>Пирог балканский</td>
                            <td style="text-align: center;">
                                <input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[1][1]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[1][2]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[1][3]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[1][4]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[1][5]" value="*"></td>
                        </tr>
                        <tr id="2">
                            <td>Пирог с сыром</td>
                            <td style="text-align: center;">
                                <input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[2][1]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[2][2]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[2][3]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[2][4]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[2][5]" value="*"></td>
                        </tr>
                        <tr id="3">
                            <td>Пирог с вареньем</td>
                            <td style="text-align: center;">
                                <input class="mon" style="margin-right: 10px;" type="checkbox" name="rec[3][1]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="tue" style="margin-right: 10px;" type="checkbox" name="rec[3][2]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="wen" style="margin-right: 10px;" type="checkbox" name="rec[3][3]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="thu" style="margin-right: 10px;" type="checkbox" name="rec[3][4]" value="*"></td>
                            <td style="text-align: center;">
                                <input class="fri" style="margin-right: 10px;" type="checkbox" name="rec[3][5]" value="*"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </form>
    </div> <!-- /container -->
</body>
</html>


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