javascriptjqueryruby-on-railstypeahead.jstwitter-typeahead

On typeahead selected event function is calling many times when it should one only


I have below function using typeahead.js and it binds on the input field.

The problem is I am trying to pass custom function when user will select value from dropdown.

So for the first time it send right values ( one time ) only. For the next selection it sends the same value twice. When selecting new from dropdown then it randomly send 4 times. On selection from dropdown it should pass variables only once.

$(document).on('mouseenter', '.js-ma-product-autocomplete', function (e) {

        var current_handler = $(this).attr('id');
        $('#' + current_handler).typeahead("destroy");
        var current_selected_id = $(this).siblings('.js-ma-linked-product-id').attr('id');
        var current_selected_type = $(this).siblings('.js-ma-linked-product-type').val();
        var current_selected_container = $(this).siblings('.js-ma-linked-product-container').val();
        var current_selected_btn = $(this).siblings('.js-ma-linked-product-add-btn').val();
        var initialize_master_agent_products_typeahead;

        initialize_master_agent_products_typeahead = function () {
            var master_agent_products_typeahead;
            master_agent_products_typeahead = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: {
                    url: "/productions/mas_products_autocomplete?query=%QUERY",
                    replace: function (url, uriEncodedQuery) {
                        return url.replace("%QUERY", uriEncodedQuery) + '&product_type=' + encodeURIComponent(current_selected_type)
                    },
                    filter: function (list) {
                        if (list.length == 0) {
                            $('#' + current_selected_id).val('');
                        }
                        return list;
                    }
                }
            });
            master_agent_products_typeahead.initialize();
            $('#' + current_handler).typeahead(null, {
                displayKey: "name",
                source: master_agent_products_typeahead.ttAdapter(),
                templates: {empty: "<div> No matching products found </div>"}
            });
            $('#' + current_handler).one('typeahead:selected', function (event, datum, name) {
                var count = 1;
                $('#' + current_selected_id).val(datum.id);
                show_options(current_selected_type);
                create_fields(current_selected_id, current_selected_type, current_selected_container, current_selected_btn, datum.id, datum.name, count++); // from this part its calling more than once.
            });
        };
        initialize_master_agent_products_typeahead();
    });

function create_fields(c_p_id, c_p_type, c_p_container, c_p_btn, l_p_id, l_p_name, count){
    // var minNumber = 300;
    // var maxNumber = 400;
    // var randomNumber = randomNumberFromRange(minNumber, maxNumber);

    // debugger;

    console.log(c_p_id);
    console.log(c_p_type);
    console.log(c_p_container);
    console.log(c_p_btn);
    console.log(l_p_id);
    console.log(l_p_name);
    console.log(count);
    console.log('*****************');

    //here it sends values multiple times

}

See below I typed once only and it shows as: enter image description here enter image description here enter image description here


Solution

  • After going back and forth with different options I came to the point that I am initializing typeahead again on each mouseenter.

    So, a fix would be to call it only once per field not all the time. And using one on it will make it work like a charm.

    Here is final working code:

    $('.js-ma-product-autocomplete').one('mouseenter', function (e) {
    
            var current_handler = $(this).attr('id');
    
            console.log(current_handler);
    
            $('#' + current_handler).typeahead("destroy");
            var c_p_id = $(this).siblings('.js-ma-product-id').val();
            // var c_lp_id = $(this).siblings('.js-ma-linked-product-id').attr('id');
            var c_p_type = $(this).siblings('.js-ma-linked-product-type').val();
            var c_container = $(this).siblings('.js-ma-linked-product-container').val();
            var c_btn = $(this).siblings('.js-ma-linked-product-add-btn').val();
            var initialize_master_agent_products_typeahead;
    
            initialize_master_agent_products_typeahead = function () {
                var master_agent_products_typeahead;
                master_agent_products_typeahead = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    remote: {
                        url: "/productions/mas_products_autocomplete?query=%QUERY",
                        replace: function (url, uriEncodedQuery) {
                            return url.replace("%QUERY", uriEncodedQuery) + '&product_type=' + encodeURIComponent(c_p_type)
                        },
                        filter: function (list) {
                            if (list.length == 0) {
                                //$('#' + c_lp_id).val('');
                            }
                            return list;
                        }
                    }
                });
                master_agent_products_typeahead.initialize();
                $('#' + current_handler).typeahead(null, {
                    displayKey: "name",
                    source: master_agent_products_typeahead.ttAdapter(),
                    templates: {empty: "<div> No matching products found </div>"}
                });
                $('#' + current_handler).on('typeahead:selected', function (event, datum, name) {
                    // $('#' + c_lp_id).val(datum.id);
                    show_options(c_p_type);
                    create_fields(c_p_id, c_p_type, c_container, c_btn, datum.id, datum.name);
                });
            };
            initialize_master_agent_products_typeahead();
        });
    
        function show_options(type) {
            if (type == 'compatible') {
                $('#subsidize_rent_lease_options').removeClass('hide');
            }
        }
    
        function create_fields(c_p_id, c_p_type, c_p_container, c_btn, c_lp_id, c_lp_name){
    
            var randomNumber = randomNumberFromRange(300, 400);
    
            console.log(c_p_id);
            console.log(c_p_type);
            console.log(c_p_container);
            console.log(c_btn);
            console.log(c_lp_id);
            console.log(c_lp_name);
    
            $("#" + c_btn).removeAttr('disabled', false);
    
            var item_container = $('<div/>', {'class': "div_" + randomNumber});
    
            $('<input>').attr({
                type: 'hidden',
                name: "product[linked_products_attributes]["+randomNumber+"][product_id]",
                value: c_p_id
            }).appendTo(item_container);
    
            $('<input>').attr({
                type: 'hidden',
                name: "product[linked_products_attributes]["+randomNumber+"][linked_product_id]",
                value: c_lp_id
            }).appendTo(item_container);
    
            $('<input>').attr({
                type: 'hidden',
                name: "product[linked_products_attributes]["+randomNumber+"][link_type]",
                value: c_p_type
            }).appendTo(item_container);
    
            $('<input>').attr({
                type: 'hidden',
                name: "product[linked_products_attributes]["+randomNumber+"][name]",
                value: c_lp_name
            }).appendTo(item_container);
    
            $("#" + c_p_container).append(item_container);
    
        }
    
        function randomNumberFromRange(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        }