Hi, there is a code:

$('#k0').click(function(){var z0=$('#c0').val();if ($("#c0:checked").length == 0) {$('#c0').prop("checked", true);var a=z0;$("#k0").css({'opacity':'0.1'});} else {var a="off";$('#c0').prop("checked", false);$("#k0").css({'opacity':'1'});}}); $('#k1').click(function(){var z1=$('#c1').val();if ($("#c1:checked").length == 0) {$('#c1').prop("checked", true);var a=z1;$("#k1").css({'opacity':'0.1'});} else {var a="off";$('#c1').prop("checked", false);$("#k1").css({'opacity':'1'});}}); $('#k2').click(function(){var z2=$('#c2').val();if ($("#c2:checked").length == 0) {$('#c2').prop("checked", true);var a=z2;$("#k2").css({'opacity':'0.1'});} else {var a="off";$('#c2').prop("checked", false);$("#k2").css({'opacity':'1'});}}); $('#k3').click(function(){var z3=$('#c3').val();if ($("#c3:checked").length == 0) {$('#c3').prop("checked", true);var a=z3;$("#k3").css({'opacity':'0.1'});} else {var a="off";$('#c3').prop("checked", false);$("#k3").css({'opacity':'1'});}}); $('#k4').click(function(){var z4=$('#c4').val();if ($("#c4:checked").length == 0) {$('#c4').prop("checked", true);var a=z4;$("#k4").css({'opacity':'0.1'});} else {var a="off";$('#c4').prop("checked", false);$("#k4").css({'opacity':'1'});}}); 

Tried to shorten it ... Something does not work .. Tell me where is the error?

 var i = 0; while (i < 4) { $('#k' + i).click(function(){ var 'z' + i = $('#c' + i).val(); if ($("#c" + i + ":checked").length == 0) { $('#c' + i).prop("checked", true); var a = 'z' + i; $("#k" + i).css({'opacity':'0.1'}); } else { var a = "off"; $('#c' + i).prop("checked", false); $("#k" + i).css({'opacity':'1'}); } }); i++; } 

And is it possible to shorten this?

 if ($('form input:checked#c0').val()) { cards["0"] = 'on'; } if ($('form input:checked#c1').val()) { cards["1"] = 'on'; } if ($('form input:checked#c2').val()) { cards["2"] = 'on'; } if ($('form input:checked#c3').val()) { cards["3"] = 'on'; } if ($('form input:checked#c4').val()) { cards["4"] = 'on'; } 
  • 2
    If you call the same handler for different elements, it's time to think about adding a class name to this element and choosing these elements by class. - tutankhamun

1 answer 1

If you look closely, the functions are practically the same, except for the value of id, which can be taken from the element that was clicked. Plus declared a few variables, the values ​​of which are not used anywhere.

 $('#k1').click(function() { var z1 = $('#c1').val(); // не используется if ($("#c1:checked").length == 0) { $('#c1').prop("checked", true); var a = z1;// не используется $("#k1").css({ 'opacity': '0.1' }); } else { var a = "off"; // не используется $('#c1').prop("checked", false); $("#k1").css({ 'opacity': '1' }); } }); 

The mistake of your approach is that the functions created during the cycle capture the variable i - the value of which will be checked only during the execution of the function. IIFE (self-calling functional expressions) can be used for corrections.

But, since hanging event handlers in jQuery can be applied to several selected elements (the loop is already inside), it is enough to collect the necessary id in the selector and add a click handler to it.

In the end, everything can be reduced to

 $('#k0,#k1,#k2,#k3,#k4').click(function() { var $this = $(this), id = $this.attr('id'), // #k0..5 idNum = id.replace(/\D/g,''), //0..5 $c = $('#c'+id), $k = $('#k'+id); $c.prop('checked', !$c.prop('checked')); $k.css({ 'opacity': $c.prop('checked') ? '0.1' : '1' }); }); 

In this case, you need to dynamically collect / only selector:

 '#k0,#k1,#k2,#k3,#k4' 

eg:

 new Array(5).join().split(',').map(function(_, index){ return '#k'+index }).join(); // "#k0,#k1,#k2,#k3,#k4" 

About the code

 if ($('form input:checked#c0').val()) { cards["0"] = 'on'; } if ($('form input:checked#c1').val()) { cards["1"] = 'on'; } if ($('form input:checked#c2').val()) { cards["2"] = 'on'; } if ($('form input:checked#c3').val()) { cards["3"] = 'on'; } if ($('form input:checked#c4').val()) { cards["4"] = 'on'; } 

Of course, this can be reduced, because again the code is repeated.

 $('form input:checked').each(function(){ //бежим в цикле по выбранным чекбоксам var $this = $(this),//получаем jQuery объект для текущего проверяемого элемента id = $this.attr('id').replace(/\D/g,'');// получаем цифры из id if($this.val()){ //проверяем значение cards[id] = 'on'; // выставляем нужный элемент в массиве } }); 
  • Thank. The second code used. Difficult for my understanding so far javascript - Alex
  • @ Alex, what's the second one? :) It's hard for my understanding so far javascript - but I thought that I painted it in detail. - Grundy