In this registration system I’m currently coding, I have a custom Zend form to deal with a group of checkbox/input pairs (which I’ll post about later). For Zend forms, these come out with names like fieldname[row][number][whichfield]. Yep, three sets of square brackets. Fun fun!
It works great for the Zend form repopulating and stuff, but not so much on the front end. This fields have some JavaScript that loops over the groups, checks the state of the checkbox, and finds its paired input to makes sure that if the checkbox is checked, we have at least something in the input and visa versa.
$(".multiple-choice-with-quantity").each(function(){ var selectedOption = $(this).val(); var myInput = $(this).attr("name").replace("[checkbox]", "[text]"); console.log($(this).prop("name")); console.log(myInput); });
The problem is, calling the name attribute on the checkbox field isn’t yielding that long name…instead I just get: fieldname[].
This sucks because the input is the same name except the value of whichfield changes. I had planned to simply take the current checkbox’s name and replace that whichfield value to get the name of the matching input for purposes of finding it to check its contents. But that would require me to be to actually get the name of the checkbox.
Googling around, I found ways to escape the brackets, if you need to refer to it by name, but not how to deal with getting the name in the first place.
So instead I ended up using a data element that is found on both the checkbox and the text input.
$(".multiple-choice-with-quantity").each(function(){ var selectedOption = $(this).val(); var myOptionID = $(this).data("option_id"); var myInput = $("form").find("input[type='text'][data-option_id='" + myOptionID + "']"); });