javascript - Is it possible to put 'number of chosen checkboxes limitation' in multiple forms into the loop? -


i'am creating page on user fill form consisting of multiple forms. each of these forms has different maximal number of possible answers. how minimize number of lines of code , put code loop? tried loop based on array, still don't know how change $("input[name='pytanie1']") every time loop goes through it. javascript put loop:

        $(document).ready(function () {             $("input[name='question1']").change(function () {                 var maxallowed = 2;                  var cnt = $("input[name='question1']:checked").length;                 if (cnt > maxallowed) {                     $(this).prop("checked", "");                     alert('choose max. ' + maxallowed + ' answers!');                 }             });         });          $(document).ready(function () {             $("input[name='question2']").change(function () {                 var maxallowed = 3;                  var cnt = $("input[name='question2']:checked").length;                 if (cnt > maxallowed) {                     $(this).prop("checked", "");                     alert('choose max. ' + maxallowed + ' answers!');                 }             });         });          $(document).ready(function () {             $("input[name='question3']").change(function () {                 var maxallowed = 3;                  var cnt = $("input[name='question3']:checked").length;                 if (cnt > maxallowed) {                     $(this).prop("checked", "");                     alert('choose max. ' + maxallowed + ' answers!');                 }             });         }); 

thanks help!

well, create array of max allowed values :

var maxallowed = [2, 3, 3]; 

and iterate :

for (var = 0; < maxallowed.length; i++) {     $(document).ready(function () {         var j = i;         $("input[name='question" + (j + 1) + "']").change(function () {             var cnt = $("input[name='question" + (j + 1) + "']:checked").length;             if (cnt > maxallowed[j]) {                 $(this).prop("checked", "");                 alert('choose max. ' + maxallowed[j] + ' answers!');             }         });      }); } 

edit : there seemed closure error in previous code. sorry


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -