UPDATE: A very big thank you to Matthew Tingey for his help with this problem. My hangup was that I was unclear on the need to add a '.req' class to the fields I want to be dynamically required. This article is where I found the code I ended up using, along with Matthew's additions. To clarify in case anyone else is similarly confused:
- .req class: add this to all fields you want to be dynamically required
- .checkbox class: add this to the field that will act as your toggle for requiring the other fields
Thanks for bearing with my mental density on this issue--I hope my struggles save others time in the future!
Hi all,
I read the top 5 threads that are returned when searching 'dynamically change required fields'. They were very helpful (especially this thread and also this one) but I just can't get the code to work with radio buttons. Another member ended the first thread asking how to make this work with radio buttons; they didn't receive a reply so I figured now might be a good time to re-ask. Any help or general JS tips will be greatly appreciated.
I copied the code contained in the first thread linked above and only made two changes, specifically the class name ('actionradio', which I added to the relevant field) and modifying the 'if' clause ('$(this[1])...'), hoping to target the first of two radio buttons within that field. Here's the code with my changes:
$(document).ready(function() { $('.actionradio input').change(function () { if ($(this[1]).is(':checked')) { $('.req span.cf-required').remove(); $('.req input').removeClass('required').removeAttr('required'); } else { $('.req label').append('<span class="cf-required">*</span>'); $('.req input').attr('required', 'True'); } }) });
My best guess is that I am using the wrong syntax (ie, "if ($(this[1]).is(':checked')") to target the first radio button to verify whether it's checked, but it seems like it should work according to other threads I read; assuming I'm on the right path, I think I just need help figuring out what number to put in the square brackets.
Thank you!
Rob