'Django - how to create a form field containing checkboxes WITH an 'Other' text input field
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,
)
Solution 1:[1]
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();
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amun_Re |
