lundi 2 septembre 2019

Onclick does not work when placing outside of the loop - Javascript

I have the current code the (i) work fine, but I would like the code to do the iClicked out of the loop, as soon as I did that, it's no longer work. How do I do that ?

I have these scripts

@section('custom-scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


<script type="text/javascript">

    let steps           = ['device', 'agent', 'ssid', 'tunnel', 'captivePortal', 'traffic'];
    let stepColors      = ['#4BB7E8', '#769BD0', '#9B83BC', '#82C341', '#53BD6D', '#30B795'];
    var selections      = [];

    var correctIndex      = 0;
    var selectedIndex     = 0;
    var agentUuid         = '';
    var agentInterfaces   = '';
    var selectedText      = 'device';
    var fadeColor         = '#4BB7E8';
    var selectedInterface = '';
    var sessionName       = '';


    $('div.col-sm-2').hide();
    $('div.col-sm-2').fadeIn(5000);
    $('div.options').hide();
    $('div.selected').hide();
    $('div.line').hide();

    function showOptions(selector) {

        var nextCircle = '';

        /*======================================
        =            Circle Clicked            =
        ======================================*/

        $('.' + selector).on("click", function() {

            selectedIndex = steps.indexOf(selector);

            if (steps.indexOf(selector) != -1) {
                nextCircle = steps[steps.indexOf(selector) + 1];
                nextIndex  = steps.indexOf(nextCircle);

                console.log('currentCircle = ', selector);
                // console.log('selectedIndex = ',steps.indexOf(selector));
                // console.log('correctIndex =', correctIndex);
                // console.log('nextCircle =', nextCircle);
                // console.log('nextIndex =', nextIndex);

                console.log('%c ---------------------------', "color: green;");

                if(selectedIndex > correctIndex){
                    alert("Please start by selecting your device.");

                    return false;
                }else{
                    $('.' + selector).off();
                }
            }

            if(selector == 'agent'){
                $('.fa.fa-plus').hide();
            }else {
                $('.fa.fa-plus').show();
            }


            let circle = $(this);
            $('div.options').fadeOut('fast');
            let currentOptions = circle.next().next('.options');
            circle.animate({backgroundColor: fadeColor }, 100);

            var data     = {};
            data.object  = selector;

            $.ajax({
                method: 'POST',
                url: `/profiles/${selector}`,
                crossDomain: true,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                    "Accept": "application/json",
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Cache-Control": "no-cache"
                },
                data: data,
                success: function(response) {

                    console.log(JSON.parse(JSON.stringify(response)));

                    for (var i = 0; i < response.length; i++) {

                        var id = response[i].replace('.','-').split(' ').join('-')

                        if(selector == 'agent'){
                            var agentName = response[i];
                        }

                        var htmlDivOption = `
                        <p id="${id}">
                        <span class="option">${id}</span>
                        <i id="${id}" class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
                        </p>

                        `;

                        currentOptions.append(htmlDivOption);

                    }

                    if(selector == 'tunnel'){

                        var htmlExtraOptions = `

                        <p id="vlan">
                        <span class="option">VLAN Tunnel</span>
                        <i class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
                        </p>

                        <p id="none">
                        <span class="option">No Tunnel</span>
                        <i class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
                        </p>

                        `;

                        currentOptions.append(htmlExtraOptions);

                    }


                    if(selector == 'agent'){

                        $.ajax({
                            method: 'POST',
                            url: `/profiles/${selector}/${agentName}`,
                            crossDomain: true,
                            contentType: false,
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                                "Accept": "application/json",
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Cache-Control": "no-cache"
                            },
                            data: data,
                            success: function(agentDetails) {

                                agentUuid = agentDetails.agent_uuid;
                                agentInterfaces = agentDetails.agent_interfaces;

                                console.log(JSON.parse(JSON.stringify(agentDetails)));
                                console.log('%c agentUuid :' + agentUuid  , "color: green;");

                            }
                        });

                    }

                    currentOptions.slideDown(100);

                    $('.popover').remove();
                    let currentPlusSign = currentOptions.find('.fa-plus');
                    currentPlusSign.on("click", function(event) {
                        $('#'+selector+'Modal').modal('show');
                    });

                    /*======================================
                    =            Option Clicked            =
                    ======================================*/

                    circle.siblings('.options').find('span.option').one("click", function(event) {

                        selectedText = $(this).closest("p").prop("id");

                        selections[selector] = selectedText;


                        if(selectedText == 'none' || selectedText == 'vlan'){
                            // alert(agentInterfaces);
                            //show interface options

                            if(selectedText == 'vlan'){
                                $(`p#none span`).unbind();
                                $(`p#${selectedText} span`).animate({"color": '#82C341'}, 100);
                            }else{
                                $(`p#vlan span`).unbind();
                                $(`p#${selectedText} span`).animate({"color": '#82C341'}, 100);
                            }

                            var htmlInterfaceSelect = `
                            <hr>
                            <div class="form-group row">
                            <label for="tunnelType" class="col-sm-6 col-form-label">Interface</label>
                            <div class="col-sm-6">
                            <select id="interface-${selectedText}">
                            <option value="default">Select your interface</option>
                            </select>
                            </div>
                            </div>`;


                            currentOptions.append(htmlInterfaceSelect);

                            var htmlInterfaceOptions = '';

                            for (i = 0; i < agentInterfaces.length; i++) {
                                console.log(agentInterfaces[i]);

                                var interfaceName    = agentInterfaces[i];
                                htmlInterfaceOptions = htmlInterfaceOptions.concat(
                                    `<option value="${interfaceName}">${interfaceName}</option>`);

                            }

                            // console.log('htmlInterfaceOptions = ',htmlInterfaceOptions);
                            // console.log(`#interface-${selectedText}`);
                            // htmlInterfaceOptions = htmlInterfaceOptions.concat('<button class="btn btn-sm btn-info "role="button"> Next </button>');

                            $(`#interface-${selectedText}`).prepend(htmlInterfaceOptions);
                            $(`#interface-${selectedText}`).slideDown(100);

                            currentOptions.slideDown(100);

                            $(`#interface-${selectedText}`).on('change', function(){

                                selectedInterface = $(this).val();
                                console.log('selectedInterface = ',selectedInterface);
                                $(this).slideUp();

                                hideOptions(circle.siblings('.options').find('span.option'), selector);
                            });

                        } else {
                            hideOptions($(this), selector);
                        }


                    });



                    $('.fa-info-circle').on("click", function(event) {

                        $('.popover').remove();
                        // $('.fa-info-circle').not(this).popover('hide');

                        let object     = $(this).parent().parent().parent().find('span').attr("circle-name");
                        let objectName = $(this).closest("p").prop("id");

                        var data        = {};
                        data.object     = object;
                        data.objectName = objectName;


                        $.ajax({
                            method: 'POST',
                            url: `/profiles/${object}/${objectName}`,
                            crossDomain: true,
                            contentType: false,
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                                "Accept": "application/json",
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Cache-Control": "no-cache"
                            },
                            data: data,
                            success: function(response) {

                                console.log(JSON.parse(JSON.stringify(response)));

                                if (response.http_code >= 200 && response.http_code <= 207) {


                                    var dataContent = '';

                                    console.log("object = ", object);
                                    console.log("objectName = ", objectName);

                                    $('.fa-info-circle#'+objectName).attr("data-original-title", response.name);

                                    if(object == 'device'){
                                        dataContent = `
                                        <p><strong>flow_type</strong> : ${response.flow_type} </p>
                                        <p><strong>subscriber_type</strong> : ${response.subscriber_type} </p>`;
                                    }else if(object == 'agent'){
                                        dataContent = `
                                        <p><strong>uuid</strong> : ${response.agent_uuid} </p>
                                        <p><strong>hostname</strong> : ${response.hostname} </p>`;
                                    }else if(object == 'ssid'){
                                        dataContent = `
                                        <p><strong>uuid</strong> : ${response.name} </p>
                                        <p><strong>ssid</strong> : ${response.ssid} </p>
                                        <p><strong>vlan</strong> : ${response.vlan} </p>`;
                                    }else if(object == 'tunnel'){
                                        dataContent = `
                                        <p><strong>uuid</strong> : ${response.name} </p>
                                        <p><strong>encap_type</strong> : ${response.encap_type} </p>
                                        <p><strong>tunnel_mac</strong> : ${response.tunnel_mac} </p>`;
                                    }else if(object == 'captiveportal'){
                                        dataContent = `
                                        <p><strong>login_success_msg</strong> : ${response.login_success_msg} </p>
                                        <p><strong>logout_url</strong> : ${response.logout_url} </p>
                                        <p><strong>submit_button_value</strong> : ${response.submit_button_value} </p>`;
                                    }else if(object == 'traffic'){
                                        dataContent = `
                                        <p><strong>name</strong> : ${response.name} </p>
                                        <p><strong>enable_speedtest</strong> : ${response.enable_speedtest}</p>`;
                                    }else{}


                                    objectName = objectName.replace('.','-').split(' ').join('-');

                                    console.log('objectName = ',objectName);

                                    $('.fa-info-circle#'+objectName).attr('data-content',dataContent);
                                    $('.fa-info-circle#'+objectName+'[data-toggle="popover"]').popover('show');

                                } else {

                                    //console.log('%c -------->> Error <<--------', "color: red;");

                                }

                            },
                            error: function(jqXHR, textStatus, errorThrown) {
                                console.log(JSON.stringify(jqXHR));
                                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                            }
                        });
                    });


                }
            });

});

}



for (i = 0; i < steps.length; i++) {
    showOptions(steps[i], stepColors[i]);
}

$('#sessionName').keyup(function() {
    this.value = this.value.replace(/\s/g, '');
});


</script>


@include('layouts.admin.sessions.create.scripts.addGlow')
@include('layouts.admin.sessions.create.scripts.hideOptions')
@include('layouts.admin.sessions.create.scripts.launch')
@include('layouts.admin.sessions.create.scripts.save')

@stop


addGlow.blade.php

<script type="text/javascript">

    /*===============================
    =            addGlow            =
    ===============================*/

    function addGlow(selector) {

        fadeColor = stepColors[selectedIndex];

        // console.log('selectedIndex = ', selectedIndex);
        // console.log('fadeColor = ', fadeColor);

        selector.css("-webkit-box-shadow", "0 0 5px " + fadeColor, 100);
        selector.css("-moz-box-shadow", "0 0 5px " + fadeColor, 100);
        selector.css("box-shadow", "0 0 5px " + fadeColor, 100);
    }

</script>


hideOptions.blade.php

<script type="text/javascript">

    // console.log($(window).width());
    // console.log(window.devicePixelRatio);

    /*====================================
    =            Hide Options            =
    ====================================*/

    function hideOptions(currentObject, selector) {

        $(currentObject).parent().parent().slideUp("slow", function() {

            fadeColor = stepColors[steps.indexOf(selector)];
            //console.log('fadeColor = ', fadeColor);

            $(this).next('.selected').text(selectedText).fadeIn(100);
            $(this).next('.selected').css({"color": fadeColor }, 100);
            $(this).next('.selected').css("border", "3px solid " + fadeColor, 100);

            addGlow($(this).next('.selected'));

            if (selector != 'traffic') {

                correctIndex++;

                $(this).prev('.line').fadeIn('fast');

                if(window.devicePixelRatio < 1.2){

                    if ($(window).width() < 2500  && $(window).width() >= 2400 ) {
                        var width = '375px';
                    } else if ($(window).width() < 2400  && $(window).width() >= 2133 ) {
                        var width = '300px';
                    } else if ($(window).width() < 2133  && $(window).width() >= 1920 ) {
                        var width = '300px';
                    } else if ($(window).width() < 1920 && $(window).width() >= 1745) {
                        var width = '250px';
                    } else if ($(window).width() < 1745 && $(window).width() >= 1536) {
                        var width = '200px';
                    } else{}

                } else {


                    if ($(window).width() < 2000  && $(window).width() >= 1800 ) {
                        var width = '300px';
                    } else if ($(window).width() < 1800  && $(window).width() >= 1600 ) {
                        var width = '200px';
                    } else if ($(window).width() < 1600  && $(window).width() >= 1440 ) {
                        var width = '200px';
                    } else if ($(window).width() < 1440 && $(window).width() >= 1309) {
                        var width = '150px';
                    } else if ($(window).width() < 1309 && $(window).width() >= 1152) {
                        var width = '100px';
                    } else{}

                }

                console.log('lineWidth = ', width);
                $(this).prev('.line').animate({"width": width}, 1100);
                addGlow($(this).prev('.line'));

                $('span.'+selector).animate({backgroundColor: fadeColor }, 100);
            }

            $('.popover').remove();

            // console.log(selections);
            // console.log(typeof JSON.parse(JSON.stringify(selections)))
            // console.log(Object.keys(selections).length);

            if (Object.keys(selections).length == $('.circle-icon').length) {
                // console.log(selections);

                $('#sessionNameModal').modal('show');

                $('#launch').on('click', function() {

                    sessionName = $('#sessionName').val();
                    launch(selections);
                });
            }

        });
    }
</script>


launch.blade.php

<script type="text/javascript">

    /*==============================
    =            launch            =
    ==============================*/

    function launch(selections) {

        console.log('selections = ', selections);

        var data               = {};
        data.clientProfile     = selections.device;
        data.agent             = selections.agent;
        data.ssidProfile       = selections.ssid;
        data.tunnelProfile     = selections.tunnel;
        data.trafficProfile    = selections.traffic;
        data.sessionName       = sessionName;
        data.agentUuid         = agentUuid;
        data.selectedInterface = selectedInterface;

        console.log("data", data);

        $.ajax({
            method: 'POST',
            url: '/sessions/store',
            crossDomain: true,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                "Accept": "application/json",
                "Content-Type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-cache"
            },
            data: data,
            success: function(response) {
                console.log('response = ', response);
                if (response.http_code >= 200 && response.http_code <= 207) {

                    toastr.options = {
                        "debug": false,
                        "newestOnTop": true,
                        "positionClass": "toast-top-right",
                        "closeButton": true,
                        "progressBar": false
                    };

                    console.log('%c -------->> Success <<--------', "color: green;");
                    toastr.success(sessionName + ' launched !');
                    window.location.replace("/sessions");

                } else {
                    toastr.options = {
                        "debug": false,
                        "newestOnTop": true,
                        "positionClass": "toast-top-right",
                        "closeButton": true,
                        "progressBar": false
                    };

                    toastr.error('can not launch.');

                }

            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });

    }

</script>


save.blade.php

<script type="text/javascript">

    /*============================
    =            save            =
    ============================*/

    function save(objectName,formId) {


        var inputs = [];
        $("form#" + formId + " :input").each(function(){
            console.log($(this).val()); // This is the jquery object of the input, do what you will

            var name = $(this).attr('name');
            var value = $(this).val();

            inputs[name] = value;

        });

        var object = $.extend({}, inputs);

        // console.log("object", object);

        $.ajax({
            method: 'POST',
            url: '/profiles/' + objectName + '/store',
            crossDomain: true,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                "Accept": "application/json",
                "Content-Type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-cache"
            },
            data: object,
            success: function(response) {
                console.log('response = ', response);
                if (response.http_code >= 200 && response.http_code <= 207) {

                    toastr.options = {
                        "debug": false,
                        "newestOnTop": true,
                        "positionClass": "toast-top-right",
                        "closeButton": true,
                        "progressBar": false
                    };

                    console.log('%c -------->> Success <<--------', "color: green;");
                    toastr.success('created');
                    //window.location.replace("/sessions");


                    //hide modal;
                    $('#'+objectName+'Modal').modal('hide');


                    //rendering the list

                    var data     = {};
                    data.object  = objectName;

                    $.ajax({
                        method: 'POST',
                        url: `/profiles/${objectName}`,
                        crossDomain: true,
                        contentType: false,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
                            "Accept": "application/json",
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Cache-Control": "no-cache"
                        },
                        data: data,
                        success: function(response) {

                            console.log(JSON.parse(JSON.stringify(response)));
                            var options = JSON.parse(JSON.stringify(response));
                            var lastItem = options[options.length-1];
                            console.log(lastItem);

                            var htmlDivOption = `
                            <p id="${lastItem}">
                            <span class="option">${lastItem}</span>
                            <i id="${lastItem}" class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
                            </p>

                            `;

                            console.log('objectName =',objectName);
                            console.log($('#'+objectName).next().next('.options'));

                            $('.'+objectName).next().next('.options').append(htmlDivOption);
                            $('.'+objectName).next().next('.options').last().hide().fadeIn(200);

                            //return false;

                        }
                    });

                } else {
                    toastr.options = {
                        "debug": false,
                        "newestOnTop": true,
                        "positionClass": "toast-top-right",
                        "closeButton": true,
                        "progressBar": false
                    };

                    toastr.error('can not create.');

                }

            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });

    }

</script>

I need some good suggestions on how can I do to refactor this a bit more.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire