I have a table with a checkbox field, what I want to do is, if the checkbox field is checked, one text field turn to required
Question
Question
Required field in a table with checkbox
Replies
Currently the only way to make a field required/optional based on conditions is through custom JavaScript.
However, if the field is only going to have data when the checkbox is selected, you could use a SHOW/HIDE rule to SHOW it when the checkbox is selected and set it to "Ignore" the values.
That way, when the checkbox is not selected, the field is hidden and it ignores the "required" attribute. Once you check the box, the field is displayed and the "required" attribute is enforced.
I've done this with tables before and it should automatically handle each row separately if you set it up right.
How can I do this configuration to works like I want
I don't really have a good example for you because having a table with a variable number of rows really complicates things.
First, you would need a javascript function that can add/remove the "required" attribute from the field.
Something like this
function setRequired(required,e){ if(required){ e.attr('required',true); } else { e.removeAttr('required').parsley().validate(); } }
For this function, you would pass in a true/false value along with the field object. For example
setRequired(false,$('.test1 input'));
Would make the input with class 'test1" not required
You would need to assign an event handler to the check boxes. Each time the checkbox changes, you need to evaluate
$(this).prop("checked")
To see what true/false you're passing over, then you need a way to isolate the field that's in the same row as the checkbox and pass that object over as well.
Maybe you could grab the parent tr element, set a custom CSS class for the target field, then only grab matching objects from within the same tr parent?
The tricky part is that each time you add another row to the table, you have to trigger an event to assign the event handler so it works in each row.
There's a lot of different ways you could do this so it is going to take some trial and error to get exactly what you want.