jrsinclair / jquery-dependent-questions

A jQuery plugin for showing/hiding form elements based on the answers to previous questions.
MIT License
16 stars 6 forks source link

checkboxes with input type=hidden default values idiom #3

Open ckruse opened 10 years ago

ckruse commented 10 years ago

Hey,

lots of frameworks generate an <input type="hidden" name="check" value="default"> directly before the checkbox when using a checkbox. This leads to a problem with this plugin: it assumes that the checkbox isn't a multi plugin and its value is always the default value.

I did the following patch to get it working:

@@ -88,16 +88,19 @@

             elType = el.attr("type");
             multi  = contains(multiInputs, elType);
-            if (!multi) { return el.val(); }
+            if (!multi && (el.length < 1 || $(el[0]).attr('type') != 'hidden')) { return el.val(); }

             if (elType === "radio") { return el.filter(":checked").val(); }

-            if (elType === "checkbox") {
-                checkVals = $.map(el.filter(":checked"), function (checkbox) {
-                    return $(checkbox).val();
-                });
-                return checkVals;
+            checkVals = $.map(el.filter(":checked"), function (checkbox) {
+                return $(checkbox).val();
+            });
+
+            if($(el[0]).attr("type") == 'hidden' && checkVals.length === 0) {
+                checkVals = [$(el[0]).val()];
             }
+
+            return checkVals;
         }

         // Event handler for when a toggling element changes value.

This is not the most beautiful solution, but at least it works.

marcus-hiles commented 5 years ago

lol @ckruse messy code alright, but watever gets the code working 👍 Wrote a similar plugin, will be sharing it on my page soon https://marcus-hiles.com/