jQuery Validation using the class instead of the name value

前端 未结 7 1297
清酒与你
清酒与你 2020-11-29 00:09

I\'d like to validate a form using the jquery validate plugin, but I\'m unable to use the \'name\' value within the html - as this is a field also used by the server app. Sp

7条回答
  •  伪装坚强ぢ
    2020-11-29 00:41

    Here's my solution (requires no jQuery... just JavaScript):

    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 4)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
    

    Put this in a script block at the end of and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

    Here, I'll even give you a test page (paste it into a file and try it):

    
    
    
    
    
    
    
    
    
    
    
    
    

提交回复
热议问题