This comes down to a common problem people run into with collections and tables. You're adding your event handler after the document ready event, which occurs before those additional fields exist.
Basically, this is what's happening
- Your form loads
- The ready event fires
- The existing radio button(s) get the handler
- The user adds a new row
- The new rows don't work...
To fix this, you would need to reassign the handlers each time the user adds a row. So, try the following instead.
- Create a separate function outside of document ready that assigns the handlers to the radio button
- Create another separate function that handles the actions
- Add a call to the event handler function in document ready
- Attach the "actions" function instead of putting to code in directly
- Add a click event handler to the "add row" link that also calls the separate function
Now, the following will happen instead
- Your form loads
- The ready event fires
- Your event handler function is called
- The existing row(s) get the handler
- User adds a row
- Your event handler function is called
- The existing row(s) get the handler
- Repeat...
Now you could run into some issues here. For example, if you call your event handler function multiple times, it could also add the same handler multiple times.
To prevent this, (assuming you use the method above) you could try using the following approach to bind the event
.off('change',classUpdate).on('change',classUpdate);
What this does is unbind the action first (if it is attached) so that you ensure there's only ever one attached.
Your code would then look something like this
$(document).ready(function(){
// Assign to existing fields
radioEvents();
// Run update when rows are added
$('.yourTableClass .cf-table-add-row').on('click',function(){
radioEvents();
});
});
function radioEvent(){
// Unbind and rebind event handler
$('.rbutton input[type=radio]').off('change',classUpdate).on('change',classUpdate);
}
// your existing function
function classUpdate(){
var radioValue = $(this).val();
console.log(radioValue)
if (radioValue == 1){
$("#q136").removeClass('goal');
$("#q136").removeClass('resource');
$("#q136").addClass('action');
}
else if (radioValue == 2){
$("#q136").removeClass('goal');
$("#q136").addClass('action');
$("#q136").addClass('resource');
}
else if (radioValue == 0){
$("#q136").removeClass('action');
$("#q136").removeClass('resource');
$("#q136").addClass('goal');
}
}
You'll need to update the selector for the table row-add event either with the id of the table or a custom class you add.
NOTE: I have not tested this code, so there may be things that need to be fixed/adjusted, but it will point you in the right direction.