Darwin Tech
Darwin Tech

Reputation: 18929

Django ModelChoiceField - select option via JQuery without removing options

I have a form like so:

class ProjectInfoForm(forms.Form):
    module = forms.ModelChoiceField(
        queryset=Module.objects.all().order_by('name'),
    )
    ...

And in my template I have some jQuery which I want to use for selecting an option form the module dropdown:

  $('#id_module').append('<option value="foo" selected="selected">Foo</option>');

However, this actually removes all the original options, which I want to be still available. So I want to select FOO but have the other options available in the drop down below FOO.

Upvotes: 0

Views: 806

Answers (1)

mVChr
mVChr

Reputation: 50185

If you want to select an existing option you can use the following:

$('#id_module').find('option[value="foo"]').attr('selected', true);

Upvotes: 3

Related Questions