my select2 jquery only work for the first form
Asked Answered
H

5

5

i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms

this is my snippet

<tbody class="tbody tb1 " id="form_set">
                    
                    {% for item in items.forms %}
                    <tr class="p-0 col-12">
                        
                        

                        <td class="">
                            <div class="col-12 p-0 mt-3 inp">
                                <input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz">
                                
                            </div>
                        </td>
                
                        <td class="">
                            <div class="col-12 p-0 mt-3 inp">
                                {{item.price | add_class:'col-12 '}}
                
                            </div>
                        </td>
                
                        <td class="">
                            <div class="col-12 p-0 mt-3 inp">    
                                {{item.quantity | add_class:'col-12 '}}
                            </div>
                        </td>
                        <td class="">
                            <div class="col-12 p-0 mt-3 inp">
                                {{item.model | add_class:'col-12 0model model' | attr:'id:model'}}
                                
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
                
<script type="text/javascript">
    $(function(){
        $('.tb1 tr:last').formset({
            prefix:'{{items.prefix}}',
            addText:'add',
            deleteText:'remove',
            addCssClass:'btn btn-success',
        });
    })
</script>

<script type="text/javascript">
        $(document).ready(function(){
            $("#model").select2()
        })
</script>

but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe? thanks

Head answered 14/6, 2020 at 14:43 Comment(0)
W
4

First of all I would love to see a little bit more, for example how you actually define your formset. It is not also clear to me what are you trying to do here. Please paste more data.

I would suggest that you think about using django-select2 module that helps a lot with handling select2 stuff in django.

I am also not sure what you mean by "how to set number of forms", maybe you wish to include some incremental counter that can be done with {{ forloop }} inside for/endfor loop?

Please paste more stuff and answer will be better.

Wallie answered 14/6, 2020 at 15:49 Comment(2)
i used inlineformset (parent ,child,form ,extra=1) in my child form i have dropdown foreignkey chooses , for the first form select2 worked fine , thanks for your suggestion i will try it .Head
beside django-select2, I wouls also recommend to also check django-dynamic-formset which allows for dynamic adding rows to your inline formset. But, beware that there are some issues concerning current code, so please check this fork: github.com/Dowsley/django-dynamic-formset/commit/…Wallie
H
3

The selector you are using to initialize select2 #model is for element ids, which should be unique for each element in the DOM.

In most browsers the effect will be that only the first instance of an element id will be recognized, and the rest ignored as if they don't exist.

In this instance you want to use a class selector: .model. This will ensure select2 is initialized for all elements that have the class "model". So the code to initialize select2 would be:

<script type="text/javascript">
    $(document).ready(function(){
        $(".model").select2()
    })
</script>
Hazardous answered 11/7, 2020 at 21:4 Comment(5)
Can you share what the html from the Loop section looks like after it is parsed by the template engine? That might help in figuring out what the issue is. You can get that from DevTools in Chrome/Firefox or the "View page source" option if you right click anywhere on the page.Hazardous
there is no issues , but it provide default id named (id_sitems_set-0-model) and for second child form (id_sitems_set-1-model) , maybe i should set a counter , and the class still remain as the first formHead
You could do that, but I still think it will be easier to use a class that is common to each of the elements that you want to use select2. What classes are assigned to that field in each of the forms?Hazardous
thanks i solved https://mcmap.net/q/1999549/-my-select2-jquery-only-work-for-the-first-formHead
This works but what if we have more than one form which has different names?Cletus
A
0

You have to reinitialize(like this way: $("#model").select2();) the select2 for other pages when they appear.

Angy answered 7/7, 2020 at 22:25 Comment(0)
P
0

You should need separately initialize with different ids.

for example:

<script type="text/javascript">
    $(document).ready(function(){
        $("#id_1").select2();
        $("#id_2").select2();
    })
</script>
Parrisch answered 13/7, 2020 at 9:35 Comment(0)
C
0

the way I found is sending the number of forms through context then apply for loop in the template.

views.py

get_context_data()

 context.update({
            "accessoryNum": len(StoreRequestAccessory.objects.filter(storeRequestId=self.object.pk)),
            "oneDimensionalItemNum":len(StoreRequestOneDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
            "twoDimensionalItemNum":len(StoreRequestTwoDimensionalItem.objects.filter(storeRequestId=self.object.pk)), 
        })

template.html

{% block javascripts %}
<script>
{% comment %} get accessoryNum from context {% endcomment %}
    var accessoryNum = {{accessoryNum}};

$(document).ready(function(){
        for(let i = 0; i <=accessoryNum; i++){
            $(`#id_storereq_accessory_form-${i}-accessoryId`).select2({
                placeholder: "Select a Item",
                allowClear: true
            });
        }
});

</script>

{% endblock javascripts %}
Cletus answered 27/2, 2022 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.