Django - Calling ManytoMany Field inside jQuery

385 views Asked by At

I am using Django Model field values inside a Javascript file by using the following code:

var action_type =$('#id_strength').val();

Here strength is a Charfield.

But the same doesn't work for a ManytoMany Field

var action_type =$('#id_batches').val();

Batches:

When I viewed the source code, the HTML looks like this:

<div class="related-widget-wrapper">
<select name="batches" data-field-name="batches" multiple="multiple" id="id_batches" data-is-stacked="0" class="selectfilter">
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
1

There are 1 answers

0
Rahul R On

So I did some digging and was finally able to get the JQuery to access the field. Since it is a ManytoMany select field, I just had to treat the batches as a select field.

var action_type = []
$("#id_batches").each(function(name,val) {
    action_type.push(val.value);
    });

Thanks Daniel Roseman for pointing me to right direction