开发者

jquery/validation plugin/object literals: selecting multiple checkboxes

开发者 https://www.devze.com 2023-01-07 19:32 出处:网络
Ok, I\'ve tried to read up on this but I\'m stumped. Unfortunately it\'s a case of me not understanding javascript properly.

Ok, I've tried to read up on this but I'm stumped. Unfortunately it's a case of me not understanding javascript properly.

When processing a form with jqueries validation plugin, you send the variables to the php mailer using literal notation:

  submitHandler: function() { 
  $.post("includes/mail-form.php",
  {  
  age : $("#form-age-id").val(),
  email : $("#form-email-id").val(), 
  name : $("#form-name-i").val(),

Which I understand. the variable age is being assigned the value from the element. When I have multiple checkboxes though, I can't use:

$("input.checkboxes:checked').val()

as it will only select the first matched element, so i need to iterate over the multiple checkboxes using a function similar to

 var allVals = [];
 $('input.orthodontic-medical-form-disease:checked').each(function() {
         allVals.push($(this).val());
      });
 return allVals;

What I don't understand is how I assign the return value to the literal. I've tried

  submitHandler: function() { 
     $.post("includes/mail-form.php",
  {  
  age开发者_C百科 : $("#form-age-id").val(),
  email : $("#form-email-id").val(), 
  name : $("#form-name-i").val(),
         checkboxes : function(){
           var allVals = [];
    $('input.orthodontic-medical-form-disease:checked').each(function() {
         allVals.push($(this).val());
         });a
           return allVals;
         }

But I'm guessing that's assigning the actual function itself to the variable, not the returned value. Could someone help me please?


Try this:

checkboxes : $('input.orthodontic-medical-form-disease:checked').map(function() {
                 return $(this).val();
             }).get() // returns array of checked values

Alternatively, encapsulate your 'checkbox value getting' logic into a named function:

function getCheckedVals() {
    var rv = $('input.orthodontic-medical-form-disease:checked').map(function() {
                 return $(this).val();
             }).get();
    return rv;
}

and just call it:

checkboxes: getCheckedVals()
0

精彩评论

暂无评论...
验证码 换一张
取 消