Click here to Skip to main content
15,920,655 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi all,
I’ve two issues

The first one:
as you can see in the second image (when cloning select input with select2 plugin, the cloned input appears with (the first disabled item appended next to the main input in every row)).

[Original row image]

[My issue image]

the second issue:
I’ve ajax code to append “unit menu” based on “product menu” selection
when I create a new row, and select an item from “product menu” I expected that the “unit menu” of the same row must affect and append the “unit list” belongs to the selection of the "product menu" in the same row.
But the behavior according to the next code is very different (after cloning the main row, when I select a product the appended unit list (appears in all unit menu in every row) and after I used ("this" or "the new created class") I get an empty "unit menu" in the new rows (i.e when select a product no changes takes place in the "unit menu")
Only the first row works (select a product append a menu to "unit input menu")

JavaScript
### js.html file
 
<script>
    $(document).ready(function() {
 
        var purchase = $('.purchase-row').last().clone();
        let purchaseCount = 0;
        
        $(document).on('click', '.add_item', function() {
            // $(".select2").select2();
            var clone = purchase.clone(); //.prop('id', 'product_' + purchaseCount);
            // var clone = purchase.clone().prop('class', 'product_' + purchaseCount);
            console.log('clone: ', clone);
            $(this).prevAll('.purchase-row').first().after(clone.hide());
            clone.slideDown('fast');
            
            // $('#product_'+ purchaseCount).find('#id_pro-product').removeClass('product').addClass('newProduct');
            // $('#product_'+  purchaseCount).find('#id_pro-unit').removeClass('unit').addClass('newUnit');
            $('.purchase-row').find('#id_pro-product').removeClass('product').addClass('newProduct');
            $('.purchase-row').find('#id_pro-unit').removeClass('unit').addClass('newUnit');
 
            $('.purchase-row').find('#id_pro-product').addClass('product_'+ purchaseCount);
            $('.purchase-row').find('#id_pro-unit').addClass('unit_'+ purchaseCount);
            // Bind an event
            // $('.newProduct').on('select2:select', function (e) { 
            //     console.log('select event');
            // });
            // The next code for reinitialize select2 
            // var $example = $(".js-programmatic-init").select2();
            var $example = $(".newProduct").select2();
            $example.select2();
 
            // ($(".newProduct").select2().select2());
            // $(".js-programmatic-init").select2();
            // $('.purchase-row').find('.product').addClass('newProduct');
            // $('.purchase-row').find('.unit').addClass('newUnit');
            purchaseCount++;
            console.log('PURCHASE-COUNT: ', purchaseCount);// $(this).parent().slideUp('fast');
            
        });
 
        $(document).on('click', '.purchase-minus', function() {
            if (purchaseCount == 0) {
                // Do nothing.
                alert('You can not delete this row' );
            } else {
                $(this).closest('.purchase-row').remove();
                purchaseCount--;
                console.log('PURCHASE-COUNT2: ', purchaseCount);// $(this).parent().slideUp('fast');2
 
            }
        });
 
        $(document).on('click', '.purchase-broom', function() {
            // $(this).closest('.purchase-row').find('select').val(0);
            $(this).closest('.newProduct').select2('destroy');
            $(this).closest('.purchase-row').find('select')[0].selectedIndex=0;
            // $(this).closest('.purchase-row').find('input').val('');
 
        });
 
 
        $(document).on('change', '.product', function(e){
            var product_id = $(this).val();
            console.log('SUCCESS-CHANGE-PRODUCT: ', product_id);
            $.ajax({
                type: 'POST',
                url: '{% url "purchases:get_product_unit" %}',
                // dataType: 'json',
                // async: true,
                // cache: false,
                data: {
                    'pro-product': $('.purchase-row select').closest('.product').val(), // this is right
                    // find('#id_pro-product')
                },
                success: function (data) { 
                    console.log(
                        'FROM SUCCESS: ', data['unit'],
                    );
                    var values_3 = data['unit'];
                    // $('#id_pro-unit').text('');
                    // $('select').closest('.unit').find('select').text('');
                    $('select').closest('.unit').text('');
                    if (values_3.length > 0) {
                        
                        for (var i = 0; i < values_3.length; i++) {
                            // $('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
                            $('select').closest('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
                        }
                    }
        
                },
                error: function (){
                    console.log('ERROR with ajax request in Adding Purchase !!!');
                },
            });
            e.preventDefault();
        });
 
        $(document).on('change', '.newProduct', function(e){
            var product_id = $(this).val();
            var $this = $(this);
            // $('select').find('#id_pro-product').addClass('product_'+ product_id + '_' + purchaseCount);
            // $('select').find('#id_pro-unit').addClass('unit_'+ product_id + '_' + purchaseCount);
            console.log('SUCCESS-CHANGE-PRODUCT-FROM-NEW-CLASS: ', product_id);
            $.ajax({
                type: 'POST',
                url: '{% url "purchases:get_new_row_unit" %}',
                // dataType: 'json',
                // async: true,
                // cache: false,
                data: {
                    'pro-product': product_id,
                    // $('#product_'+purchaseCount).closest('.newProduct select').val(),
                    // find('#id_pro-product')
                },
                success: function (data) { 
                    console.log(
                        'FROM SUCCESS-NEW-CLASS: ', data['unit'],
                        'PRODUCT-FROM-NEW-CLASS: ', data['product'],
                    );
                    var values_3 = data['unit'];
                    // $('#id_pro-unit').text('');
                    $('select').closest('.unit_'+purchaseCount).text('');
                    if (values_3.length > 0) {
                        
                        for (var i = 0; i < values_3.length; i++) {
                            $('.purchase-row select').closest('.unit_'+ purchaseCount).append('<option>' + values_3[i] + '</option>');
                            // $('.newUnit select').closest('#product_'+ purchaseCount).append('<option>' + values_3[i] + '</option>');
                            // $('select').closest('#product_'+ purchaseCount).find('.newUnit').append('<option>' + values_3[i] + '</option>');
                            // $('.newUnit select').closest('.unit_'+purchaseCount).append('<option>' + values_3[i] + '</option>');
                        }
                    }
        
                },
                error: function (){
                    console.log('ERROR with ajax request in Adding Purchase-New Class !!!');
                },
            });
            e.preventDefault();
        });
 
 
    });
 
</script>




[Pastebin link]

[Codepen link]

By the way I'm using Django so the inputs will not appear correctly in codepen link
Sorry for prolongation.... Thanks

What I have tried:

Also I tried to add a new class with append the "purchaseCount" when click on the cloning button, But I failed ..

JavaScript
$('.purchase-row').find('#id_pro-product').removeClass('product').addClass('product_'+purchaseCount);
$('.purchase-row').find('#id_pro-unit').removeClass('unit').addClass('unit_'+purchaseCount); 
Posted
Updated 8-Feb-23 5:38am
Comments
Member 15627495 4-Feb-23 2:43am    
it's a 'selectors' mistake.it leads to a badly done 'append'.
$('select option').append(.....);


by selecting 'select' tag , you're adding another 'select' area.

for your goal, you have to write IN the 'select'. It's 'option' to add inside the 'select'.

to shorten your selection by 'selectors'
you can :
$('.purchase-row').find('#id_pro-product').
become :
$('.purchase-row #id_pro-product') // all #id_product next to '.purchase-row' inside '.purchase-row'
$('.purchase-row > #id_pro-product') // all childrens inner '.purchase-row' with the '#id_pro_product' as id.

one more thing, #id must stay single, or you'll have buggy calls with #id 
amr aly 4-Feb-23 4:12am    
First of all thanks for replying .
I already tried what you suggested (Really it appends the "unit menu" in the same row but also in all above rows)
I'm using this
for (var i = 0; i < values_3.length; i++) {
   $('.purchase-row #id_pro-unit').append('<option>' + values_3[i] + '</option>');
}
Member 15627495 4-Feb-23 4:28am    
append() apply on 'after' the 'last element' of 'your selector'.

Maybe use anothers identifiers ( plural ) for a better reconition of the tag you want to change.
replace '.purchase-row' by id="".with differents id="area_this"/ id="area_that", belonging to the existing area.
amr aly 4-Feb-23 7:11am    
What's the ( identifiers ( plural ) ), sorry I'm not understand what you are meaning.
And I can't get (
replace '.purchase-row' by id="".with differents id="area_this"/ id="area_that", belonging to the existing area.
)
I'm so sorry but I'm not understand what should I do
amr aly 5-Feb-23 5:57am    
Really I don't know what should I do , because I'm new to using cloning option and I enhance my skills so I need help to understand what I miss here in my code

Thanks ....

1 solution

Thanks @Member 15627495 and I can't forget your advises
But I took time to fix it as follow with one ajax call

JavaScript
$(document).on('change', '.product', function(e){
            var product_id = $(this).val();
            let $el = $(this).closest('.purchase-row');
            console.log('SUCCESS-CHANGE-PRODUCT: ', product_id,);
            $.ajax({
                type: 'POST',
                url: '{% url "purchases:get_product_unit" %}',
                data: {
                    'pro-product': product_id,
                },
                success: function (data) { 
                    if (purchaseCount == 0) {
                        console.log('purchase count equal to ZERO: ');
                        console.log(
                            'FROM SUCCESS: ', data['unit'],
                        );
                        var values_3 = data['unit'];               
                        if (values_3.length > 0) {
                        
                            for (var i = 0; i < values_3.length; i++) {
                                $el.find('.unit').append('<option>' + values_3[i] + '</option>');
                            }
                        }
                    } else {
                        let unit = $el.find('.newUnit'); // here I can access the "unit input" of the same row of the "product input"
                        var values_3 = data['unit'];
                        unit.text('');
                        console.log('COUNT IS NOT EQUAL TO ZERO:', values_3);
                        if (values_3.length > 0) {
                            for (var i = 0; i < values_3.length; i++) {
                                unit.append('<option>' + values_3[i] + '</option>');
                            }
                        }
                    }
        
                },
                error: function (){
                    console.log('ERROR with ajax request in Adding Purchase !!!');
                },
            });
            e.preventDefault();
        });



Also I got help ideas from the following links. Indeed they are very useful links

- Link-1[^]
- Link-2[^]
- Link-3[^]
- Link-4[^]
- [Link5 ^]
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900