I'm creating a form in Django, and would like to give users a list of checkboxes with the option of having an Other _____ text input as one of the choices. Here's my code using MultipleChoiceField
and CheckboxSelectMultiple
:
class IntakeFormSimple(Form):
def __init__(self, *args, **kwargs):
super(IntakeFormSimple, self).__init__(*args, **kwargs)
preferred_pronouns = forms.MultipleChoiceField(
choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them")), # <--- add "Other" here
label="What are your preferred pronoun(s)?",
widget=forms.CheckboxSelectMultiple,
)
CodePudding user response:
You need to use a CharField
or TextField
instead of MultipleChoiceField
. Then you need to create a custom widget which is a combination of MultipleSelect
and TextInput
widgets. I suggest using a MultiWidget
to add these two widgets together (https://docs.djangoproject.com/en/4.0/ref/forms/widgets/#multiwidget) and adding the "Other" checkbox purely decoratively which uses some JS to enable/disable the text input. To do this you will need to use custom widget template.
I am suspecting that you will also need to override the field class too to make it work with your custom widget.
I hope I pointed you in the right direction.
CodePudding user response:
Add the "other" field to your Form:
class IntakeFormSimple(Form):
def __init__(self, *args, **kwargs):
super(IntakeFormSimple, self).__init__(*args, **kwargs)
preferred_pronouns = forms.MultipleChoiceField(
choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them", "other")),
label="What are your preferred pronoun(s)?",
widget=forms.CheckboxSelectMultiple,
)
Now in your javascript file, hide that input when page loads:
$("#user-input-textbox").hide();
Finally, use the 'other' radio button is checked and hide it when it is unchecked and also clear the existing value before hiding:
$('#Other').click(function(){
if ($(this).is(':checked')){
$("#user-input-textbox").show();
}
else{
$("#user-input-textbox").html('');
$("#user-input-textbox").hide();
}
});